package com.cci.kangdao.service.impl;

import com.alibaba.fastjson.JSON;
import com.cci.kangdao.common.RedisKeys;
import com.cci.kangdao.common.type.NotifyMannerType;
import com.cci.kangdao.crmapi.CRMApiUtils;
import com.cci.kangdao.crmapi.CRMRequestMapToAppMapUtils;
import com.cci.kangdao.crmapi.CRMResponeEntity;
import com.cci.kangdao.crmapi.CRMServiceConst;
import com.cci.kangdao.dao.*;
import com.cci.kangdao.dao.model.*;
import com.cci.kangdao.entity.*;
import com.cci.kangdao.escalation.dao.EscalationOrderTDao;
import com.cci.kangdao.escalation.dao.EscalationReasonTDao;
import com.cci.kangdao.escalation.dao.EscalationSolutionTDao;
import com.cci.kangdao.escalation.model.EscalationOrderT;
import com.cci.kangdao.escalation.model.EscalationReasonT;
import com.cci.kangdao.escalation.model.EscalationSolutionT;
import com.cci.kangdao.escalation.model.type.TypeDictionary;
import com.cci.kangdao.escalation.service.EscalationNotifyService;
import com.cci.kangdao.escalation.service.EscalationService;
import com.cci.kangdao.escalation.service.impl.EscalationServiceImpl;
import com.cci.kangdao.model.condition.CloseWorkOrderCondition;
import com.cci.kangdao.redis.RedisClientUtils;
import com.cci.kangdao.service.*;
import com.cci.kangdao.task.AsyncTask;
import com.cci.kangdao.utilTool.*;
import com.cci.kangdao.wechatOrder.dao.WeChatSmsLinkTokenTDao;
import com.cci.kangdao.wechatOrder.enums.CompanyEnum;
import com.cci.kangdao.wechatOrder.model.WeChatSmsLinkTokenT;
import com.cci.kangdao.wechatOrder.service.IWeChatNoticeService;
import net.sf.json.JSONArray;
import net.sf.json.JSONException;
import net.sf.json.JSONObject;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.collections4.MapUtils;
import org.apache.commons.collections4.map.HashedMap;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.ResponseHandler;
import org.apache.http.util.EntityUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.net.URLDecoder;
import java.text.DecimalFormat;
import java.util.*;
import java.util.stream.Collectors;

//crm同步到app相关接口
@Service("CRMPlatformService")
public class CRMPlatformServiceImpl implements CRMPlatformService {

	private final static Logger LOG = Logger.getLogger(CRMPlatformServiceImpl.class);

	private String msgbody = "您有新工单信息，工单号 ***，";
	private String msgtitle = "新工单提醒";
	private String transmsg = "您有新工单信息，工单号 ***，";
	private String SALESSERVICE_TYPE = "售前检查";

	private int msgFunctionNew = 1;// 字典项(用户在线报修修提醒)
	private int msgCategoryNew = 1;// 字典项（新工单提醒）

	private static final Integer BATCH_LIMIT = 100;


	@Value("${cci.mt.virtualStation.stationNo}")
	private String stationNo;


	@Value("${cci.mt.virtualStation.stationName}")
	private String stationName;



	@Autowired
	private PropertiesUtils propertiesUtils;

	@Resource
	private WorkOrderRepairDao workOrderRePairDao;

	@Resource
	private AsyncTask asyncTask;

	@Autowired
	private WorkOrderTServiceImpl workOrderTServiceImpl;

	@Resource
	private WorkOrderDrDao workOrderDrDao;

	@Autowired
	private UserTDao userTDao;
	@Resource
	private LoginDao loginDao;
	@Resource
	private CRMPlatformServiceDao crmServiceDao;
	@Resource
	private CompanyTDao companyTDao;
	@Resource
	private EngineMsgDao engineMsgDao;
	@Resource
	private WorkOrderPicsDao workOrderPicsDao;

	@Resource
	private ServiceStationDao serviceStationDao;

	@Autowired
	private RedisClientUtils redisClientUtils;
	@Resource
	private ServiceModelNameDao serviceModelNameDao;
	@Resource
	private EngineerQualifyTDao engineerQualifyTDao;
	@Resource
	private SSHasSMNDao ssHasSMNDao;
	@Resource
	private SSRepairTDao ssRepairTDao;
	@Resource
	private SSHasCompanyDao ssHasCompanyDao;
	@Resource
	private SSHasServiceTypeDao ssHasServiceTypeDao;
	@Resource
	private SSHasVehicleTypeDao ssHasVehicleTypeDao;
	@Resource
	private SSHasEngineTypeDao ssHasEngineTypeDao;
	@Resource
	private CRMLogService crmLogService;
	@Resource
	private DictionariesTService dictionariesTService;
	@Resource
	private WorkOrderOperatorRelationDao operatorRelationDao;
	@Resource
	private NoticeService noticeService;
	@Resource
	private WorkOrderTDao workOrderTDao;

	@Resource
	private DBUMessageService dbuMessageService;

	@Resource
	private WorkOrderRemedyPictureDao workOrderRemedyPictureDao;

	@Resource
	private PartInfoTDao partInfoTDao;

	@Resource
	private EngineTypeTDao engineTypeTDao;
	@Resource
	private PositionUserTDao positionUserTDao;

	@Resource
	private OrderManageDao orderManageDao;

	@Resource
	private WorkOrderTService workOrderTService;

	@Resource
	private AsyncCrmService asyncCrmService;

	@Resource
	private EscalationService escalationService;

	@Resource
	private WorkOrderFlowTDao workOrderFlowTDao;

    @Resource
    private WorkOrderRepairDao workOrderRepairDao;

	@Resource
	private WorkOrderPrincipalTDao workOrderPrincipalTDao;


	@Autowired
	private CRMSendSMSMsgDao crmSendSMSMsgDao;

	@Autowired
	private WeChatSmsLinkTokenTDao weChatSmsLinkTokenTDao;

	@Autowired
	private IWeChatNoticeService weChatNoticeService;

	@Autowired
	private WorkOrderOperatorRelationDao workOrderOperatorRelationDao;


	@Autowired
	private UserHasRolesTDao userHasRolesTDao;

    @Resource
	private EngineerQualifyWithsmnTMapper qualifyWithsmnTMapper;
	@Resource
	private ExceptionDataSyncCrmTDao exceptionDataSyncCrmTDao;
	@Autowired
	private CRMPlatformServiceDao platformServiceDao;

	@Resource
	private WorkOrderSynchroService workOrderSynchroService;

	@Resource
	private PositionTMapper positionTMapper;

	@Resource
	private WorkOrderIndividualCasesMapper workOrderIndividualCasesMapper;

	@Resource
	private CampaignTaskFlowDao campaignTaskFlowDao;
	@Resource
	private CampaignTaskInfoDao campaignTaskInfoDao;


	@Override
	@Transactional
	public ModelAndView createWorkOrderFromCRM(Map<String, Object> httpMap) {

		HttpServletRequest request = (HttpServletRequest) httpMap.get("request");
		HttpServletResponse response = (HttpServletResponse) httpMap.get("response");

		LOG.info(String.format("crm创建服务工单同步工单信息 参数params：%s", httpMap.get(CRMServiceConst.CRM_REQUEST_PARAMS)));

		/**
		 * 1、将CRM请求参数转化成APP系统请求参数
		 */
        //解析dcec的加密参数
        if (httpMap.get("company") != null && "DCEC".equals(httpMap.get("company"))) {
            if (httpMap.get("params") != null) {
                try {
                    String params = URLDecoder.decode(httpMap.get("params").toString(), "UTF-8");
                    LOG.info(String.format("dcec crm创建服务工单同步工单信息 参数params解析：%s", params));
                    httpMap.put("params", params);
                } catch (Exception e) {
                    LOG.info("dcec crm创建服务工单同步工单信息 参数params解析：失败");
                    e.printStackTrace();
                }
            }
        }
		@SuppressWarnings("unchecked")
        //URLDecoder.decode(httpMap.get("params").toString(), "UTF-8");
		Map<String, Object> requestMap = (Map<String, Object>) JSONObject
				.fromObject(httpMap.get(CRMServiceConst.CRM_REQUEST_PARAMS).toString());

		String company = httpMap.get(CRMServiceConst.CRM_REQUEST_COMPANY).toString();
		if (company.equals(CRMServiceConst.DBU)) {

			// 将CRM传递数据转化成APP 后台字段
			Map<String, Object> orderMap = CRMRequestMapToAppMapUtils.workOrderFieldCreateFromDBU(requestMap);

			/**
			 * 2、定义数据保存/更新结果
			 */
			// 保存工单返回结果
			int saveResult = -1;
			// 获取工单信息参数
			JSONObject resultObj = this.crmCreatWorkOrderByDBU(orderMap);

			if (resultObj != null) { // 异常情况
				// 返回客户
				ParameterTool.writeResponse(response, resultObj.toString());
				resultObj = null;
				return null;
			}
            String serviceSubtype = MapUtils.getString(orderMap, "ServiceSubtype").trim();
            switch (serviceSubtype) {
                case "首保":
                    serviceSubtype = "首次保养";
                    break;
                case "保养":
                    serviceSubtype = "保养记录";
                    break;
                case "BIS服务":
                    serviceSubtype = "厂内服务";
                    break;
                case "统修":
                    serviceSubtype = "统修整改";
                    break;
                case "故障维修":
                    serviceSubtype = "故障处理";
                    break;
            }
            orderMap.put("ServiceSubtype", serviceSubtype);
            int i = workOrderTDao.getcountByOrderNoCrm((String) orderMap.get("OrderNoCrm"));
//            if(i > 0){
//				LOG.info("工单保存失败,CRM号已存在");
//				JSONObject jObject = new JSONObject();
//				jObject.put("status", 1);
//				jObject.put("msg", "工单保存失败，CRM号已存在");
//				jObject.put("data", new JSONObject());
//				// 返回客户
//				ParameterTool.writeResponse(response, jObject.toString());
//				jObject = null;
//				return null;
//			}
			// 保存新工单
			saveResult = crmServiceDao.CreateWorkOrder(orderMap);
			// 保存推荐的三家服务商与工单关系
			if (MapUtils.getIntValue(orderMap, "IsHaveDBEngineer", 0) == 1) {
				int saveReStationResult = crmServiceDao.saveRecommendThreeStationToTable(orderMap);
			}
			if (saveResult > 0) {
				{
					// 保存到WorkOrderOperatorRelationDao
					Map<String, Object> operatorRelationMap = new HashMap<>();
					operatorRelationMap.put("OrderId", orderMap.get("OrderId"));
					operatorRelationMap.put("OrderStatus", orderMap.get("OrderStatus"));
					operatorRelationMap.put("Name", orderMap.get("DBEngineerName"));
					operatorRelationMap.put("Phone", orderMap.get("DBEngineerPhone"));
					operatorRelationMap.put("Creator", 1);
					operatorRelationMap.put("CreateTime", orderMap.get("CreateTime"));
					List<UserT> DBEngineerUsers = loginDao.getUserByPhone(orderMap.get("DBEngineerPhone").toString());
					if (DBEngineerUsers != null && DBEngineerUsers.size() > 0) {
						long DBEngineerUsersId = DBEngineerUsers.get(0).getId();
						operatorRelationMap.put("UserId", DBEngineerUsersId);
					}
					operatorRelationMap.put("Flag", 0);
                    // TODO 把获取的区域工程师区域地址放入参数Map中
                    crmPositionNameIntoMap(operatorRelationMap);
					operatorRelationDao.insertOperatorRelationInfo(operatorRelationMap);
				}
				// 保存工单负责人表
				JSONObject result = this.saveWorkOrderPrincipalAndMessageInfoFromDBU(orderMap);
				if (result != null) {
					ParameterTool.writeResponse(response, result.toString());
					result = null;
					return null;
				}
			} else {
				LOG.info("工单保存失败");
				JSONObject jObject = new JSONObject();
				jObject.put("status", 1);
				jObject.put("msg", "工单保存失败，请重试");
				jObject.put("data", new JSONObject());
				// 返回客户
				ParameterTool.writeResponse(response, jObject.toString());
				jObject = null;
				return null;
			}
			JSONObject jObject = new JSONObject();
			jObject.put("status", 0);
			jObject.put("msg", "CRM工单信息同步成功");
			jObject.put("data", new JSONObject());
			// 返回客户
			ParameterTool.writeResponse(response, jObject.toString());
			jObject = null;
			return null;

			/**
			 * DCEC amt需求  12-16
			 */
		} else if (company.equals(CRMServiceConst.DCEC)) {
			// 将CRM传递数据转化成APP 后台字段
			/**
			 * DCEC amt工单需求 2022-12-26
			 * 新增3个参数
			 * 【变速箱序列号】，amtNo
			 * 【保修性质】，warrantyNature
			 * 【故障发生时间】，faultHappenTime
			 */
			Map<String, Object> orderMap = CRMRequestMapToAppMapUtils.workOrderFieldCreate(requestMap);

			/**
			 * 2、定义数据保存/更新结果
			 */
			// 保存工单返回结果
			int saveResult = -1;
			// 更新工单返回结果
			int updateResult = -1;

			/**
			 * 3、保存工单信息
			 */
			if (orderMap.get("OrderSource").equals("4")) {// 400工单改派

				// 根据旧工单编号查询旧工单id
				Map<String, Object> oldWorkOrder = crmServiceDao
						.getOldOrderInfoByOrderNo(orderMap.get("APPOrderNo").toString());

				/**
				 * DCEC amt 需求
				 * 修改 12-27 添加amt逻辑
				 */
				JSONObject resultObj = this.crmCreatWorkOrder(orderMap);
				if (resultObj != null) { // 异常情况
					// 返回客户
					ParameterTool.writeResponse(response, resultObj.toString());
					resultObj = null;
					return null;
				}
				orderMap.put("WorkHours", MapUtils.getString(oldWorkOrder, "WorkHours", ""));
				orderMap.put("WorkMileages", MapUtils.getString(oldWorkOrder, "WorkMileages", ""));
				orderMap.put("CreateTime", oldWorkOrder.get("CreateTime"));
				orderMap.put("RelOrderIdOld", oldWorkOrder.get("ID"));
				orderMap.put("OrderSource", oldWorkOrder.get("OrderSource".toString()));
				// 生成新工单

                // 当单子状态为 待服务经理审核时     服务站查询时不可查，  -1为不可查询
                if ("2".equals(orderMap.get("OrderStatus"))) {
                    orderMap.put("isShowStation", -1);
                }
				LOG.info("***********************************App转换的参数为：" + orderMap) ;
				saveResult = crmServiceDao.CreateWorkOrder(orderMap);

				// 新工单id
				Map<String, Object> oldWorkOrderReMap = new HashedMap<String, Object>();
				Long newOrderId = MapUtils.getLong(orderMap, "OrderId");
				oldWorkOrderReMap.put("RelOrderId", newOrderId);
				oldWorkOrderReMap.put("oldOrderId", oldWorkOrder.get("ID"));
				// 旧工单关联新工单表id
				crmServiceDao.updateRelOrderId(oldWorkOrderReMap);

				if (saveResult > 0) {
					JSONObject result = this.saveWorkOrderPrincipalAndMessageInfo(orderMap);
					if (result != null) {
						ParameterTool.writeResponse(response, result.toString());
						result = null;
						return null;
					}
				} else {
					LOG.info("工单保存失败");
				}
			} else if (orderMap.get("OrderSource").equals("2")) {// 400工单报修

				JSONObject resultObj = this.crmCreatWorkOrder(orderMap);
				if (resultObj != null) { // 异常情况
					// 返回客户
					ParameterTool.writeResponse(response, resultObj.toString());
					resultObj = null;
					return null;
				}
                // 当单子状态为 待服务经理审核时     服务站查询时不可查，  -1为不可查询
                if ("2".equals(orderMap.get("OrderStatus"))) {
                    orderMap.put("isShowStation", -1);
                }
				int i = workOrderTDao.getcountByOrderNoCrm((String) orderMap.get("OrderNoCrm"));
//				if(i > 0){
//					LOG.info("工单保存失败,CRM号已存在");
//					JSONObject jObject = new JSONObject();
//					jObject.put("status", 1);
//					jObject.put("msg", "工单保存失败，CRM号已存在");
//					jObject.put("data", new JSONObject());
//					// 返回客户
//					ParameterTool.writeResponse(response, jObject.toString());
//					jObject = null;
//					return null;
//				}
				saveResult = crmServiceDao.CreateWorkOrder(orderMap);
				if (saveResult > 0) {
					JSONObject result = this.saveWorkOrderPrincipalAndMessageInfo(orderMap);
					if (result != null) {
						ParameterTool.writeResponse(response, result.toString());
						result = null;
						return null;
					}
				} else {
					LOG.info("工单保存失败");
				}
			} else if (orderMap.get("OrderSource").equals("3")) { // 服务站CRM工单报修

				JSONObject resultObj = this.crmCreatWorkOrder(orderMap);
				if (resultObj != null) { // 异常情况
					// 返回客户
					ParameterTool.writeResponse(response, resultObj.toString());
					resultObj = null;
					return null;
				}
                // 当单子状态为 待服务经理审核时     服务站查询时不可查，  -1为不可查询
                if ("2".equals(orderMap.get("OrderStatus"))) {
                    orderMap.put("isShowStation", -1);
                }
				int i = workOrderTDao.getcountByOrderNoCrm((String) orderMap.get("OrderNoCrm"));
//				if(i > 0){
//					LOG.info("工单保存失败,CRM号已存在");
//					JSONObject jObject = new JSONObject();
//					jObject.put("status", 1);
//					jObject.put("msg", "工单保存失败，CRM号已存在");
//					jObject.put("data", new JSONObject());
//					// 返回客户
//					ParameterTool.writeResponse(response, jObject.toString());
//					jObject = null;
//					return null;
//				}
				saveResult = crmServiceDao.CreateWorkOrder(orderMap);
				if (saveResult > 0) {
					JSONObject result = this.saveWorkOrderPrincipalAndMessageInfo(orderMap);
					if (result != null) {
						ParameterTool.writeResponse(response, result.toString());
						result = null;
						return null;
					}
				} else {
					LOG.info("工单保存失败");
				}
			} else if (orderMap.get("OrderSource").equals("5")) { // 用户APP报单没有指派服务站，400指派服务站之后

				Map<String, Object> oldWorkOrderMap = crmServiceDao
						.getOldOrderInfoByOrderNo(orderMap.get("APPOrderNo").toString());
				JSONObject resultObj = this.updateWorkOrder(orderMap, oldWorkOrderMap);
				if (resultObj != null) { // 异常情况
					// 返回客户
					ParameterTool.writeResponse(response, resultObj.toString());
					resultObj = null;
					return null;
				}
				oldWorkOrderMap.put("NatureClaim", orderMap.get("NatureClaim"));
				oldWorkOrderMap.put("AmtNo", orderMap.get("AmtNo"));
				oldWorkOrderMap.put("WarrantyNature", orderMap.get("WarrantyNature"));
				oldWorkOrderMap.put("FaultHappenTime", orderMap.get("FaultHappenTime"));
				updateResult = crmServiceDao.updateWorkOrderInfo(oldWorkOrderMap);
				if (updateResult > 0) {
					oldWorkOrderMap.put("OrderId", oldWorkOrderMap.get("ID").toString());
					JSONObject result = this.saveWorkOrderPrincipalAndMessageInfo(oldWorkOrderMap);
					if (result != null) {
						ParameterTool.writeResponse(response, result.toString());
						result = null;
						return null;
					}
				} else {
					LOG.info("工单保存失败");
				}
			} else {// 工单来源传递不正确
				JSONObject obj = new JSONObject();
				// 未查询到审核人，不能创建工单
				obj.put("status", 1);
				obj.put("msg", "工单来源不正确");
				obj.put("data", new JSONObject());
				// 返回客户
				ParameterTool.writeResponse(response, obj.toString());
				obj = null;
				return null;

			}

			JSONObject obj = new JSONObject();
			obj.put("status", 0);
			obj.put("msg", "CRM工单信息同步成功");
			obj.put("data", new JSONObject());
			// 返回客户
			ParameterTool.writeResponse(response, obj.toString());
			obj = null;
			return null;
		} else if (company.equals(CRMServiceConst.XCEC)) {
			String cmrNo = MapUtils.getString(requestMap, "CRMNo", ""); //crmNo  必传
			// 加锁处理，避免发生多次提交。
			if (!redisClientUtils.lock(cmrNo, 60L)) {
				//防止同一时间创建两条工单
				ParameterTool.writeErrorResponse(response, -98);
				return null;
			}
			//防止工单创建流程走完，网卡等原因crm有同步过来一条一样的工单信息
			//根据crmNo获取工单
			Map<String, Object> workOrderByCrmNo = workOrderTDao.getWorkOrderByOrderNoCrm(cmrNo);
			if (MapUtils.isNotEmpty(workOrderByCrmNo)) {
				//根据crmNo能查出工单，并且工单状态不在异常关闭和服务站拒单里,不能创建工单
				if (MapUtils.getIntValue(workOrderByCrmNo, "OrderStatus") != 16
						&& MapUtils.getIntValue(workOrderByCrmNo, "OrderStatus") != 5) {
					ParameterTool.writeErrorResponse(response, -97);
					return null;
				}
			}

			// 将CRM传递数据转化成APP 后台字段
			Map<String, Object> orderMap = CRMRequestMapToAppMapUtils.workOrderFieldCreateFromXCEC(requestMap);

			/**
			 * 2、定义数据保存/更新结果
			 */
			// 保存工单返回结果
			int saveResult = -1;
			// 更新工单返回结果
			int updateResult = -1;
			/**
			 * 3、保存工单信息
			 */
			if (orderMap.get("OrderSource").equals("4")) {// 400工单改派

				// 根据旧工单编号查询旧工单id
				Map<String, Object> oldWorkOrder_XCEC = crmServiceDao
						.getOldOrderInfoByOrderNo(orderMap.get("APPOrderNo").toString());

				JSONObject resultObj = this.crmCreatWorkOrder(orderMap);
				if (resultObj != null) { // 异常情况
					// 返回客户
					ParameterTool.writeResponse(response, resultObj.toString());
					resultObj = null;
					return null;
				}

				orderMap.put("WorkHours", MapUtils.getString(oldWorkOrder_XCEC, "WorkHours", ""));
				orderMap.put("WorkMileages", MapUtils.getString(oldWorkOrder_XCEC, "WorkMileages", ""));
				orderMap.put("CreateTime", oldWorkOrder_XCEC.get("CreateTime"));
				orderMap.put("RelOrderIdOld", oldWorkOrder_XCEC.get("ID"));
				orderMap.put("OrderSource", oldWorkOrder_XCEC.get("OrderSource".toString()));
				// 生成新工单
				saveResult = crmServiceDao.CreateWorkOrder(orderMap);

				// 新工单id
				Map<String, Object> oldWorkOrderReMap = new HashedMap<String, Object>();
				Long newOrderId = MapUtils.getLong(orderMap, "OrderId");
				oldWorkOrderReMap.put("RelOrderId", newOrderId);
				oldWorkOrderReMap.put("oldOrderId", oldWorkOrder_XCEC.get("ID"));
				// 旧工单关联新工单表id
				crmServiceDao.updateRelOrderId(oldWorkOrderReMap);

				if (saveResult > 0) {
					JSONObject result = this.saveWorkorderPrincipalAndMessageInfoFromXCEC(orderMap);
					if (result != null) {
						ParameterTool.writeResponse(response, result.toString());
						result = null;
						return null;
					}
				} else {
					LOG.info("工单保存失败");
				}
			} else if (orderMap.get("OrderSource").equals("2")) {// 400工单报修

				JSONObject resultObj = this.crmCreatWorkOrder(orderMap);
				if (resultObj != null) { // 异常情况
					// 返回客户
					ParameterTool.writeResponse(response, resultObj.toString());
					resultObj = null;
					return null;
				}
				saveResult = crmServiceDao.CreateWorkOrder(orderMap);
				if (saveResult > 0) {
					JSONObject result = this.saveWorkorderPrincipalAndMessageInfoFromXCEC(orderMap);
					if (result != null) {
						if (result.get("status") != null && (int) result.get("status") == 0) {
//							Boolean synStatusFlag = MapUtils.getBoolean(orderMap, "SynStatusFlag");
//							if (synStatusFlag != null && synStatusFlag) {
//								//同步数据给crm  解决sf  不修改的问题
//								LOG.error("400 创建 客户工单，需同步工单状态--待服务经理确认，--参数为" + orderMap.toString());
//								this.syncOrderStatusToCrm(orderMap);
//							}
						}
						ParameterTool.writeResponse(response, result.toString());
						result = null;
						return null;
					}
				} else {
					LOG.info("工单保存失败");
				}
			} else if (orderMap.get("OrderSource").equals("3")) { // 服务站CRM工单报修

				JSONObject resultObj = this.crmCreatWorkOrder(orderMap);
				if (resultObj != null) { // 异常情况
					// 返回客户
					ParameterTool.writeResponse(response, resultObj.toString());
					resultObj = null;
					return null;
				}
				//是否是大工匠工单 去除
				orderMap.remove("IsTechSupport");
				//技术支持内容  去除
				orderMap.remove("TechSupportContent");
				saveResult = crmServiceDao.CreateWorkOrder(orderMap);
				if (saveResult > 0) {
					JSONObject result = this.saveWorkorderPrincipalAndMessageInfoFromXCEC(orderMap);
					if (result != null) {
						ParameterTool.writeResponse(response, result.toString());
						result = null;
						return null;
					}
				} else {
					LOG.info("工单保存失败");
				}
			} else if (orderMap.get("OrderSource").equals("5")) { // 用户APP报单没有指派服务站，400指派服务站之后

				Map<String, Object> oldWorkOrder_XCEC = crmServiceDao
						.getOldOrderInfoByOrderNo(orderMap.get("APPOrderNo").toString());
				JSONObject resultObj = this.updateWorkOrder(orderMap, oldWorkOrder_XCEC);
				if (resultObj != null) { // 异常情况
					// 返回客户
					ParameterTool.writeResponse(response, resultObj.toString());
					resultObj = null;
					return null;
				}
				updateResult = crmServiceDao.updateWorkOrderInfo(oldWorkOrder_XCEC);
				if (updateResult > 0) {
					oldWorkOrder_XCEC.put("OrderId", oldWorkOrder_XCEC.get("ID").toString());
					JSONObject result = this.saveWorkorderPrincipalAndMessageInfoFromXCEC(oldWorkOrder_XCEC);
					if (result != null) {
						ParameterTool.writeResponse(response, result.toString());
						result = null;
						return null;
					}
				} else {
					LOG.info("工单保存失败");
				}
			} else {// 工单来源传递不正确
				JSONObject obj = new JSONObject();
				// 未查询到审核人，不能创建工单
				obj.put("status", 1);
				obj.put("msg", "工单来源不正确");
				obj.put("data", new JSONObject());
				// 返回客户
				ParameterTool.writeResponse(response, obj.toString());
				obj = null;
				return null;

			}

			JSONObject obj = new JSONObject();
			obj.put("status", 0);
			obj.put("msg", "CRM工单信息同步成功");
			obj.put("data", new JSONObject());
			// 返回客户
			ParameterTool.writeResponse(response, obj.toString());
			obj = null;
			return null;
		}
		return null;

	}

	public CRMResponeEntity syncOrderStatusToCrm(Map<String, Object> orderMap) {
		Map<String, Object> parameters = new HashMap<String, Object>();
		parameters.put("orderNo", orderMap.get("OrderNo"));
		parameters.put("billStatus", orderMap.get("OrderStatus"));
		parameters.put("actionTime", "");
		parameters.put("directorName", "");
		parameters.put("directorPhone", "");
		parameters.put("refuseReason", "");
		parameters.put("phoneIMEI", org.apache.commons.collections.MapUtils.getString(orderMap, "IMEI", ""));
		parameters.put("positionLat", org.apache.commons.collections.MapUtils.getFloatValue(orderMap, "locLat", 0));
		parameters.put("positionLon", org.apache.commons.collections.MapUtils.getFloatValue(orderMap, "locLon", 0));
		parameters.put("location", org.apache.commons.collections.MapUtils.getString(orderMap, "location", ""));
		return CRMApiUtils.getCRMServiceApi().syncOrderStatusToCrm(
				CRMServiceConst.XCEC,
				platformServiceDao, redisClientUtils, parameters, null);
	}

	@Override
	@Transactional
	@SuppressWarnings("unchecked")
	public void createWorkOrderFromCCEC(Map<String, Object> map) {
		HttpServletResponse response = (HttpServletResponse) map.get("response");
		String interfaceName = "syncAppWorkOrderInfo";
		Map<String, Object> requestMap = (Map<String, Object>) JSONObject
				.fromObject(MapUtils.getString(map, CRMServiceConst.CRM_REQUEST_PARAMS));
		String company = MapUtils.getString(map, CRMServiceConst.CRM_REQUEST_COMPANY);
		if (CRMServiceConst.CCEC.equals(company)) {
			CompanyT channelCompany = companyTDao.getCompanyInfoByCompanyNo(company);
			// 查询ESN是否支持
			String esn = MapUtils.getString(requestMap, "ESN");
			Long engineMsgId = null;
			List<Map<String, Object>> handlerList = new ArrayList<>();
			if (StringUtils.isNotEmpty(esn)) {
				EngineMsg engineMsg = engineMsgDao.getEngineMsgByESNString(esn);
				if (null != engineMsg) {
					if (StringUtils.isEmpty(engineMsg.getSoNo())) {
						String message = "CCSS报修，ESN不存在，无法报单";
						ParameterTool.writeResponse(response, 1, message);
						saveToAPIExceptionT(interfaceName, message, JsonUtils.toJsonString(requestMap), company);
						return;
					} else {
						engineMsgId = engineMsg.getId();
					}
				} else {
					String message = "CCSS报修，ESN不存在，无法报单";
					ParameterTool.writeResponse(response, 1, message);
					saveToAPIExceptionT(interfaceName, message, JsonUtils.toJsonString(requestMap), company);
					return;
				}
			} else {
				String message = "CCSS报修，ESN不存在，无法报单";
				ParameterTool.writeResponse(response, 1, message);
				saveToAPIExceptionT(interfaceName, message, JsonUtils.toJsonString(requestMap), company);
				return;
			}

			// 如果服务商编号不为空，则获取服务商相关数据
			String stationNo = MapUtils.getString(requestMap, "stationNo");
			Long serviceStationId = null;
			Double guessDistance = 0.0;
			if (StringUtils.isNotEmpty(stationNo)) {
				Map<String, Object> queryMap = new HashMap<>(2);
				queryMap.put("stationNo", stationNo);
				queryMap.put("companyId", channelCompany.getId());
				List<Map<String, Object>> ssRepairList = ssRepairTDao.getSSRepairTByServiceStationNoCompanyID(queryMap);
				if (CollectionUtils.isNotEmpty(ssRepairList)) {
					Map<String, Object> ssRepairMap = ssRepairList.get(0);
					serviceStationId = MapUtils.getLong(ssRepairMap, "ServiceStationID");
					guessDistance = getGuessDistance(serviceStationId, MapUtils.getString(requestMap, "faultLon"),
							MapUtils.getString(requestMap, "faultLat"));
				}
			}

			UserT customer = null;
			String customerPhone = MapUtils.getString(requestMap, "customerPhone");
			if (StringUtils.isNotEmpty(customerPhone)) {
				customer = userTDao.getUserByPhone(customerPhone);
			}

			// 保存工单返回结果
			int saveResult;
			String orderSource = MapUtils.getString(requestMap, "orderSource");
			Integer orderStatus = null;
			if ("2".equals(orderSource)) {
				// 服务站CRM报修
				if (!NumberUtils.isPositiveNum(serviceStationId)) {
					String message = "服务商CCSS报修，服务商不可用（编号为空或未授权）" + stationNo;
					ParameterTool.writeResponse(response, 1, message);
					saveToAPIExceptionT(interfaceName, message, JsonUtils.toJsonString(requestMap), company);
					return;
				}
				orderStatus = 23;
			} else if ("3".equals(orderSource)) {
				// 400报修(用户通过400报修)
				orderStatus = 23;
			} else {
				String message = "非法OrderSource";
				ParameterTool.writeResponse(response, 1, message);
				saveToAPIExceptionT(interfaceName, message, JsonUtils.toJsonString(requestMap), company);
				return;
			}

			// 获取审核人列表
			handlerList = getHandlerList(channelCompany.getId(), serviceStationId, orderStatus);
			if (CollectionUtils.isEmpty(handlerList)) {
				String message = "CCSS报修，无审核人员信息，无法报单，服务商编号：" + stationNo;
				ParameterTool.writeResponse(response, 1, message);
				saveToAPIExceptionT(interfaceName, message, JsonUtils.toJsonString(requestMap), company);
				return;
			}

			// app创建工单Map
			Map<String, Object> appCreateOrderMap = convertCreateMapFromCrm(channelCompany, requestMap);

			// 拼装工单Map
			if (null != customer) {
				appCreateOrderMap.put("CustomerId", customer.getId());
			}
			appCreateOrderMap.put("GuessDistance", guessDistance);
			appCreateOrderMap.put("OrderStatus", orderStatus);
			appCreateOrderMap.put("EngineMsgId", engineMsgId);
			appCreateOrderMap.put("ServiceStationId",
					NumberUtils.isPositiveNum(serviceStationId) ? serviceStationId : 0L);
			/**
			 * <p>
			 *     自动生成工单编号，由 redis 更改为 sqlServer
			 * </p>
			 */
			//String orderNo = workOrderRepairService.getOrderNo(new HashMap<>(0));
			String orderNo = OrderGenerateUtil.getWorkOrderNo();
			appCreateOrderMap.put("OrderNo", orderNo);
			appCreateOrderMap.put("Creator", -1);
			appCreateOrderMap.put("CreateTime", LocalTimeUtil.getRealCurrentTime());

			// 保存工单数据
			saveResult = crmServiceDao.CreateWorkOrder(appCreateOrderMap);
			// 若保存成功，保存工单流水
			if (NumberUtils.isPositiveNum(saveResult)) {
				saveWorkOrderFlow(appCreateOrderMap, "CRM创建工单");
			} else {
				String message = "工单保存失败，请重试";
				ParameterTool.writeResponse(response, 1, message);
				saveToAPIExceptionT(interfaceName, message, JsonUtils.toJsonString(requestMap), company);
				return;
			}
			Long orderId = MapUtils.getLong(appCreateOrderMap, "OrderId");

			// 保存审核人信息
			if (CollectionUtils.isNotEmpty(handlerList)) {
				for (Map<String, Object> handlerMap : handlerList) {
					Long userId = MapUtils.getLong(handlerMap, "ID");
					workOrderTServiceImpl.savePrincipal(orderId, orderStatus, 1, userId, -1,
							LocalTimeUtil.getRealCurrentTime());
				}
			}

			// 向审核人发送通知数据
			if (CollectionUtils.isNotEmpty(handlerList)) {
				String message = null;
				switch (orderStatus) {
				// 待服务商接单， 给站长/技师/客户发信息
				case 4:
					message = String.format("您有新工单信息，工单号%s，请尽快处理。", orderNo);
					break;
				case 23:
					// 待400审核， 给400发送信息
					message = String.format("您有工单待审核，工单号%s，请尽快处理。", orderNo);
					break;
				default:
					break;
				}

				for (Map<String, Object> handlerMap : handlerList) {
					Long receiverId = MapUtils.getLong(handlerMap, "ID");
					String username = MapUtils.getString(handlerMap, "UserName");
					String userPhone = MapUtils.getString(handlerMap, "Phone");
					noticeService.push(2, 1, orderId, receiverId, username, message, message, message, -1L);
					noticeService.sendSMS(2, 1, orderId, receiverId, userPhone, message, -1L);
				}
			}

			// 向客户发送通知数据，无需求
			/*if(StringUtils.isNotEmpty(customerPhone)){
				Long receiverId = null;
				if(null != customer){
					receiverId = customer.getId();
					noticeService.push(2,1,orderId,receiverId,customer.getUserName(),"用户通知内容","用户通知内容","",-1L);
				}
				noticeService.sendSMS(2,1,orderId,receiverId,customerPhone,"用户通知内容",-1L);
			}*/

			// 响应CCSS系统
			Map<String, Object> data = new HashMap<>(1);
			data.put("APPOrderNo", orderNo);
			ParameterTool.writeSuccessResponse(response, data);
		}
	}

	private Double getGuessDistance(Long serviceStationId, String faultLon, String faultLat) {
		Double guessDistance = 0.0;
		Map<String, Object> stationMap = serviceStationDao.getServiceStationById(serviceStationId);
		if (MapUtils.isNotEmpty(stationMap)) {
			String stationLon = MapUtils.getString(stationMap, "PositionLon");
			String stationLat = MapUtils.getString(stationMap, "PositionLat");
			Map<String, Object> directionMap = GDRegion.direction(stationLon, stationLat, faultLon, faultLat);
			if (MapUtils.isNotEmpty(directionMap)) {
				Long distance = MapUtils.getLong(directionMap, "distance", 0l);
				BigDecimal driveDistance = new BigDecimal(distance);
				BigDecimal guessDistanceBig = driveDistance.divide(BigDecimal.valueOf(1000L), 2, RoundingMode.DOWN);
				if (guessDistanceBig.compareTo(BigDecimal.ZERO) > 0) {
					guessDistance = guessDistanceBig.doubleValue();
				}
			}
		}
		return guessDistance;
	}

	/**
	 * 将crm参数转换为app参数
	 *
	 * @param channelCompany
	 * @param requestMap
	 * @return
	 */
	private Map<String, Object> convertCreateMapFromCrm(CompanyT channelCompany, Map<String, Object> requestMap) {
		Map<String, Object> convertMap = new HashMap<>();
		// CRM抱怨工单编号
		String complainerOrderNo = MapUtils.getString(requestMap, "CCSSComplainerOrderNo");
		convertMap.put("OrderNoCrm", complainerOrderNo);
		String orderSource = MapUtils.getString(requestMap, "orderSource");
		switch (orderSource) {
			case "2":
				convertMap.put("OrderSource", 3);
				break;
			case "3":
				convertMap.put("OrderSource", 2);
				break;
			default:
				break;
		}
		// CRM工单编号
		String crmNo = MapUtils.getString(requestMap, "CCSSNo");
		convertMap.put("CCSSOrderNo", crmNo);
		// CRM工单编号
		// String appNo = MapUtils.getString(requestMap,"APPOrderNo");
		// CRM渠道
		String serviceChannel = MapUtils.getString(requestMap, "serviceChannel");
		convertMap.put("OrderChannel", channelCompany.getId());
		// 报单esn
		String esn = MapUtils.getString(requestMap, "ESN");
		convertMap.put("ESN", esn);
		// 报单设备号
		String equipmentNo = MapUtils.getString(requestMap, "equipmentNo");
		convertMap.put("VIN", equipmentNo);
		// 客户姓名
		String customerName = MapUtils.getString(requestMap, "customerName");
		convertMap.put("CustomerName", customerName);
		convertMap.put("ContactName", customerName);
		// 客户手机号
		String customerPhone = MapUtils.getString(requestMap, "customerPhone");
		convertMap.put("CustomerPhone", customerPhone);
		convertMap.put("ContactPhone", customerPhone);
		// 故障点纬度
		String faultLat = MapUtils.getString(requestMap, "faultLat");
		convertMap.put("LocLat", faultLat);
		// 故障点精度
		String faultLon = MapUtils.getString(requestMap, "faultLon");
		convertMap.put("LocLon", faultLon);
		// 故障地点
		String faultLocation = MapUtils.getString(requestMap, "faultLocation");
		convertMap.put("Location", faultLocation);
		// 故障描述
		String faultDesc = MapUtils.getString(requestMap, "faultDesc");
		convertMap.put("CustomerComplaint", faultDesc);
		// 报单设备号
		//String stationName = MapUtils.getString(requestMap,"stationName");
		//convertMap.put("",);
		// 报单设备号
		//String stationNo = MapUtils.getString(requestMap,"stationNo");
		//convertMap.put("",);
		// 运行时长
		String workHours = MapUtils.getString(requestMap, "workHours");
		convertMap.put("WorkHours", workHours);
		// 运行里程
		String workMileages = MapUtils.getString(requestMap, "workMileages");
		convertMap.put("WorkMileages", workMileages);
		// 是否需要外出
		String needGoOut = MapUtils.getString(requestMap, "needGoOut");
		convertMap.put("IsOutside", needGoOut);
		// 工单上报时间
		String orderCreateTime = MapUtils.getString(requestMap, "orderCreateTime");
		convertMap.put("UploadTime", orderCreateTime);
		// 报修人类型
		String repairerType = MapUtils.getString(requestMap, "repairerType", "3");
		convertMap.put("RepairerType", repairerType);

		// 抱怨单类别
		//String orderCategory = MapUtils.getString(requestMap,"orderCategory");
		//convertMap.put("ComplainOrderCategory",orderCategory);
		// 故障级别
		String faultLevel = MapUtils.getString(requestMap, "faultLevel", "");
		convertMap.put("FaultLevel", faultLevel);

		// 需求类型
		String requestType = MapUtils.getString(requestMap, "requestType", "");
		if (requestType.equals("1")) {
			convertMap.put("RequestType", "2");
		} else {
			convertMap.put("RequestType", "1");
		}

		// 服务计划
		String serviceInitPlan = MapUtils.getString(requestMap, "serviceInitPlan");
		convertMap.put("ServiceInitPlan", serviceInitPlan);

		// 出行方式
		String goutMode = MapUtils.getString(requestMap, "goutMode", "");
		if (goutMode.equals("0")) {
			convertMap.put("GoOutType", "4");
		} else if (goutMode.equals("1")) {
			convertMap.put("GoOutType", "3");
		} else if (goutMode.equals("2")) {
			convertMap.put("GoOutType", "1");
		} else if (goutMode.equals("3")) {
			convertMap.put("GoOutType", "2");
		} else {
			convertMap.put("GoOutType", "");
		}

		// 报单设备号
		//String urgencyDegree = MapUtils.getString(requestMap,"urgencyDegree");
		//convertMap.put("",);
		// 报单设备号
		//String dispatchServiceType = MapUtils.getString(requestMap,"dispatchServiceType");
		//convertMap.put("",);
		// 报单设备号
		//String factory = MapUtils.getString(requestMap,"factory");
		//convertMap.put("",);
		// 报单设备号
		//String approvalCategory = MapUtils.getString(requestMap,"approvalCategory");
		//convertMap.put("",);
		// 报单设备号
		String orderType = MapUtils.getString(requestMap, "orderType", "0");
		convertMap.put("OrderType", orderType);
		// 客户企业名称
		String customerCompany = MapUtils.getString(requestMap, "customerCompany");
		convertMap.put("CustomerCompanyName", customerCompany);
		// 2.4.0新增
		// 抱怨单类型
		String orderCategory = MapUtils.getString(requestMap, "orderCategory", "");
		convertMap.put("ComplainWorkOrderType", orderCategory);

		// 故障级别，大小鼓掌
		String sizeFailure = MapUtils.getString(requestMap, "sizeFailure", "");
		convertMap.put("SizeFailure", sizeFailure);

		// 故障原因
		String faultReason = MapUtils.getString(requestMap, "faultReason", "");
		convertMap.put("FaultReason", faultReason);
		return convertMap;
	}

	/**
	 * 保存工单流水数据
	 *
	 * @param orderMap
	 */
	private void saveWorkOrderFlow(Map<String, Object> orderMap, String processComment) {
		Map<String, Object> flowMap = new HashMap<>();
		flowMap.put("OrderId", MapUtils.getLong(orderMap, "OrderId"));
		flowMap.put("ProcessorId", MapUtils.getLong(orderMap, "Creator"));
		flowMap.put("OrderStatus", MapUtils.getLong(orderMap, "OrderStatus"));
		flowMap.put("ProcessComment", processComment);
		flowMap.put("ProLocLon", MapUtils.getDoubleValue(orderMap, "LocLon"));
		flowMap.put("ProLocLat", MapUtils.getDoubleValue(orderMap, "LocLat"));
		flowMap.put("ProLocation", MapUtils.getLong(orderMap, "Location"));
		flowMap.put("CreateTime", LocalTimeUtil.getRealCurrentTime());
		int saveOperationResult = workOrderRePairDao.saveOperation(flowMap);
		if (!NumberUtils.isPositiveNum(saveOperationResult)) {
			LOG.warn("工单记录保存失败 工单id:" + MapUtils.getString(orderMap, "OrderId"));
		}
	}

	/**
	 * 获取审核人列表
	 *
	 * @param companyId
	 * @param serviceStationId
	 * @param orderStatus
	 * @return
	 */
	private List<Map<String, Object>> getHandlerList(Long companyId, Long serviceStationId, Integer orderStatus) {
		List<Map<String, Object>> handlerList = new ArrayList<>();
		switch (orderStatus) {
			// 待服务商接单， 给站长/技师/客户发信息
			case 4:
				handlerList = workOrderRePairDao.getServiceStationManagerList(serviceStationId);
				break;
			case 23:
				// 待400审核， 给400发送信息
				handlerList = positionUserTDao.getUserListByCondition(companyId, serviceStationId, 1);
				break;
			default:
				break;
		}
		return handlerList;
	}

	@Override
	@SuppressWarnings("unchecked")
	public ModelAndView getOrderPictureInfos(Map<String, Object> httpMap) {
		HttpServletResponse response = (HttpServletResponse) httpMap.get("response");
		String company = httpMap.get(CRMServiceConst.CRM_REQUEST_COMPANY).toString();
		Map<String, Object> dataMap = new HashMap<>(2);
		Map<String, Object> requestMap = (Map<String, Object>) JSONObject
				.fromObject(httpMap.get(CRMServiceConst.CRM_REQUEST_PARAMS).toString());
		dataMap.put("orderNo", requestMap.get("orderNo"));
		List<Map<String, Object>> pictureList = new ArrayList<>();
		if ("XCEC".equals(company)) {
			//xcec需求   xcec的照片描述标志维修前和维修中
			pictureList = workOrderPicsDao.getXCECWorkOrderPics(requestMap);
			if (CollectionUtils.isNotEmpty(pictureList)) {
				for (Map<String, Object> picture : pictureList) {
					String picNo = MapUtils.getString(picture, "PicNo", "");
					if (picNo.startsWith("1")) {
						picture.put("description", "维修前-" + MapUtils.getString(picture, "description", ""));
					}
					if (picNo.startsWith("2")) {
						picture.put("description", "维修中-" + MapUtils.getString(picture, "description", ""));
					}
				}
			}
		} else {
			pictureList = workOrderPicsDao.getWorkOrderPics(requestMap);
		}
		Map<String, Object> responseMap = new HashMap<>(3);
		if (CollectionUtils.isEmpty(pictureList)) {
			dataMap.put("pictures", new ArrayList<>(0));

			responseMap.put("status", 1);
			responseMap.put("msg", "此工单暂无照片信息");
			responseMap.put("data", dataMap);
		} else {
			dataMap.put("pictures", pictureList);

			responseMap.put("status", 0);
			responseMap.put("msg", "获取工单照片信息成功");
			responseMap.put("data", dataMap);
		}
		ParameterTool.writeResponse(response, JsonUtils.toJsonString(responseMap));
		return null;
	}

	@Override
	@Transactional
	@SuppressWarnings("unchecked")
	public ModelAndView syncServiceStationInfosFromCRM(Map<String, Object> httpMap) {
		HttpServletResponse response = (HttpServletResponse) httpMap.get("response");
        HttpServletRequest request = (HttpServletRequest) httpMap.get("request");
		LOG.error("记录：同步服务站被修改的问题" + request.getRequestURL());
		String apiName = "syncStationInfo";
		String companyChannel = httpMap.get(CRMServiceConst.CRM_REQUEST_COMPANY).toString();
		String key = apiName + companyChannel;
		//防止并发
		if(!redisClientUtils.lock(key,60L)){
			ParameterTool.writeErrorResponse(response, -98);
			return null;
		}
		try {
			if (companyChannel.equals(CRMServiceConst.DBU)) {
				List<Map<String, Object>> positionList = new ArrayList<>();
				CompanyT company = companyTDao.getCompanyInfoByCompanyNo(companyChannel);

				// 从请求中获取服务站信息
				List<Map<String, Object>> serviceStationList = JSONArray
						.fromObject(httpMap.get(CRMServiceConst.CRM_REQUEST_PARAMS).toString());

				// 校验参数是否为空，如果为空返回错误信息
				if (CollectionUtils.isNotEmpty(serviceStationList)) {
					List<String> stationNoList = new ArrayList<>();

					for (Map<String, Object> map : serviceStationList) {

						// 服务站ID
						Long ssId = null;

						String stationName = MapUtils.getString(map, "stationName");
						String stationNo = MapUtils.getString(map, "stationNo");

						// 操作状态（增加1；删除2；修改3；冻结 4；解冻 5）
						String requstStatus = MapUtils.getString(map, "requstStatus");
						if (stationNoList.contains(stationNo + requstStatus)) {
							crmLogService.saveCrmErrorLog(companyChannel, apiName, JsonUtils.toJsonString(map),
									"列表中服务商操作重复" + stationNo);
							continue;
						} else {
							stationNoList.add(stationNo + requstStatus);
						}

						if (StringUtils.isEmpty(stationName) || StringUtils.isEmpty(stationNo)) {
							crmLogService.saveCrmErrorLog(companyChannel, apiName, JsonUtils.toJsonString(map),
									"服务商名称/编号为空");
							continue;
						}


						// 查询出当前服务站与当前渠道是否有授权关系
						Map<String, Object> queryMap = new HashMap<>(2);
						queryMap.put("companyId", company.getId());
						queryMap.put("stationNo", stationNo);
						List<Map<String, Object>> ssRepairList = ssRepairTDao
								.getSSRepairTByServiceStationNoCompanyID(queryMap);
						// 通过服务商名称查询服务商信息
						List<ServiceStationT> serviceStationTList = serviceStationDao
								.getServiceStationListByStationName(stationName);
						// 授权关系为空
						if (CollectionUtils.isEmpty(ssRepairList)) {

							/*
							 * 1.渠道与服务站没有授权关系
							 * 2.同步的服务站是否存在
							 * 		1：不存在
							 * 			a.保存服务站
							 * 			b.绑定渠道与服务站
							 * 		2：存在
							 *      	a.更新服务站
							 *      	b.绑定渠道与服务站
							 */

							// 当前渠道跟服务站没有授权关系
							if (requstStatus.equals("2")) {
								// 删除原编号管辖信息
								deletePositionUserServiceStation(company.getId(), stationNo);
								crmLogService.saveCrmErrorLog(companyChannel, apiName, JsonUtils.toJsonString(map),
										"未查询到服务商授权数据，无法删除");
								continue;
							}
							// 服务商主数据为空
							// 注：保存服务站信息
							if (CollectionUtils.isEmpty(serviceStationTList)) {
								// 转换为数据库MAP
								Map<String, Object> serviceStationInfoMap = getDBUServiceStationMap(map, null, company);
								// 获取地址经纬等信息
								getAddressInfo(serviceStationInfoMap, positionList);

								// 将数据存入数据库
								// 保存服务站信息
								int saveServiceStationResult = crmServiceDao
										.insertServiceStationInfo(serviceStationInfoMap);
								if (saveServiceStationResult > 0) {
									// 服务站ID
									Long serviceStationId = MapUtils.getLong(serviceStationInfoMap, "ssid");
									serviceStationInfoMap.put("CompanyID", company.getId());
									serviceStationInfoMap.put("ServiceStationID", serviceStationId);
									// 维护授权关系
									saveSSRepair(serviceStationInfoMap, SSRepairOperation.SAVE);
									saveSSHasCompany(MapUtils.getString(map, "vehicleCompanies"), company.getId(),
											serviceStationId);
									//saveSSHasServiceType(MapUtils.getString(map,"serviceType"),company.getId(),serviceStationId);
									//saveSSHasVehicleType(MapUtils.getString(map,"vehicleType"),company.getId(),serviceStationId);
									saveSSHasSMN(MapUtils.getString(map, "authorizedMode"), company.getId(),
											serviceStationId);

									// 根据插入表返回id编辑服务站序号
									Map<String, Object> updateMap = new HashedMap<String, Object>();
									String cStationNo = String.format("C" + "%05d", serviceStationId);
									updateMap.put("StationNo", cStationNo);
									updateMap.put("id", serviceStationId);
									crmServiceDao.updateStationInfoByPrimaryKey(updateMap);
									//插入dealerInfo_T需要ServiceStationID赋值
									serviceStationInfoMap.put("ServiceStationID",serviceStationId);
									saveHisDealerInfoForPortal(serviceStationInfoMap);
									// 初始化服务站id
									ssId = serviceStationId;

								} else {
									crmLogService.saveCrmErrorLog(companyChannel, apiName, JsonUtils.toJsonString(map),
											"服务商信息保存失败");
								}
							} else {
								// 理论上，同名服务商有且仅有一家
								// 注：更新服务站信息
								ServiceStationT serviceStationT = serviceStationTList.get(0);
								// 先删除该服务商授权关系，预防同服务商存在不同编号的多条授权
								ssRepairTDao.deleteSSRepairTByID(serviceStationT.getId(), company.getId());
								// 删除原编号管辖信息
								deletePositionUserServiceStation(company.getId(), stationNo);
								Map<String, Object> serviceStationInfoMap = getDBUServiceStationMap(map,
										serviceStationT.getId(), company);
								// 获取地址经纬等信息
								getAddressInfo(serviceStationInfoMap, positionList);
								serviceStationInfoMap.put("CompanyID", company.getId());
								serviceStationInfoMap.put("ServiceStationID", serviceStationT.getId());
								serviceStationInfoMap.put("id", serviceStationT.getId());
								// 更新服务商信息
								crmServiceDao.updateStationInfoByPrimaryKey(serviceStationInfoMap);
								saveHisDealerInfoForPortal(serviceStationInfoMap);
								// 插入服务商授权信息
								saveSSRepair(serviceStationInfoMap, SSRepairOperation.SAVE);
								saveSSHasCompany(MapUtils.getString(map, "vehicleCompanies"), company.getId(),
										serviceStationT.getId());
								//saveSSHasServiceType(MapUtils.getString(map,"serviceType"),company.getId(),serviceStationT.getId());
								//saveSSHasVehicleType(MapUtils.getString(map,"vehicleType"),company.getId(),serviceStationT.getId());
								saveSSHasSMN(MapUtils.getString(map, "authorizedMode"), company.getId(),
										serviceStationT.getId());

								// 初始化服务站id
								ssId = serviceStationT.getId();
							}
						} else {

							/*
							 * 1.渠道与服务站有授权关系
							 * 2.同步的服务站是否存在
							 * 		1：不存在
							 * 			a.更新服务站
							 * 			b.绑定渠道与服务站-更新
							 * 		2：存在
							 *      	a.更新服务站
							 *      	b.绑定渠道与服务站-更新
							 */

							// 授权信息不为空
							Map<String, Object> ssRepairMap = ssRepairList.get(0);
							Long ssStationId = MapUtils.getLong(ssRepairMap, "ServiceStationID");
							// 当操作为删除时
							if (requstStatus.equals("2")) {
								// 删除授权信息
								ssRepairTDao.deleteSSRepairTByID(ssStationId, company.getId());
								// 删除编号管辖信息
								deletePositionUserServiceStation(company.getId(), stationNo);
								continue;
							}
							// 非删除操作，当服务商信息为空
							if (CollectionUtils.isEmpty(serviceStationTList)) {
								// 将绑定授权关系的服务商数据更新
								Map<String, Object> serviceStationInfoMap = getDBUServiceStationMap(map, null, company);
								// 获取地址经纬等信息
								getAddressInfo(serviceStationInfoMap, positionList);
								serviceStationInfoMap.put("CompanyID", company.getId());
								serviceStationInfoMap.put("ServiceStationID", ssStationId);
								serviceStationInfoMap.put("id", ssStationId);
								// 更新服务商信息
								serviceStationInfoMap.put("SSRepairId", MapUtils.getLong(ssRepairMap, "ID"));
								crmServiceDao.updateStationInfoByPrimaryKey(serviceStationInfoMap);
								saveHisDealerInfoForPortal(serviceStationInfoMap);
								saveSSRepair(serviceStationInfoMap, SSRepairOperation.UPDATE);
								saveSSHasCompany(MapUtils.getString(map, "vehicleCompanies"), company.getId(), ssStationId);
								//saveSSHasServiceType(MapUtils.getString(map,"serviceType"),company.getId(),ssStationId);
								//saveSSHasVehicleType(MapUtils.getString(map,"vehicleType"),company.getId(),ssStationId);
								saveSSHasSMN(MapUtils.getString(map, "authorizedMode"), company.getId(), ssStationId);

								// 初始化服务站id
								ssId = ssStationId;
							} else {
								// 服务商数据不为空，判断是否是授权服务商
								ServiceStationT serviceStationT = serviceStationTList.get(0);
								// 当前服务商为授权服务商，更新所有数据
								if (ssStationId.equals(serviceStationT.getId())) {
									// 将绑定授权关系的服务商数据更新
									Map<String, Object> serviceStationInfoMap = getDBUServiceStationMap(map,
											serviceStationT.getId(), company);
									// 获取地址经纬等信息
									getAddressInfo(serviceStationInfoMap, positionList);
									serviceStationInfoMap.put("CompanyID", company.getId());
									serviceStationInfoMap.put("ServiceStationID", ssStationId);
									serviceStationInfoMap.put("id", ssStationId);
									// 更新服务商信息
									crmServiceDao.updateStationInfoByPrimaryKey(serviceStationInfoMap);
									saveHisDealerInfoForPortal(serviceStationInfoMap);
									serviceStationInfoMap.put("SSRepairId", MapUtils.getLong(ssRepairMap, "ID"));
									saveSSRepair(serviceStationInfoMap, SSRepairOperation.UPDATE);
									saveSSHasCompany(MapUtils.getString(map, "vehicleCompanies"), company.getId(),ssStationId);
									//saveSSHasServiceType(MapUtils.getString(map,"serviceType"),company.getId(),ssStationId);
									//saveSSHasVehicleType(MapUtils.getString(map,"vehicleType"),company.getId(),ssStationId);
									saveSSHasSMN(MapUtils.getString(map, "authorizedMode"), company.getId(), ssStationId);

									// 初始化服务站id
									ssId = ssStationId;
								} else {
									// 当前服务商非授权服务商，记录异常信息
									crmLogService.saveCrmErrorLog(companyChannel, apiName, JsonUtils.toJsonString(map),
											"服务商信息与数据库信息发生冲突，无法处理");
								}
							}
						}


						// ================================[DealersInfo_T]==============================
						if(!Objects.isNull(ssId)) {
							saveDealersInfo(map, ssId, company.getId());
						}

					}
				} else {
					// 同步服务商数据为空
					crmLogService.saveCrmErrorLog(companyChannel, apiName, JsonUtils.toJsonString(httpMap),
							"服务站信息同步失败，服务商数据为空");
					ParameterTool.writeResponse(response, 1, "同步失败，服务商信息为空");
					return null;
				}

				// 服务商地址信息同步
				if (CollectionUtils.isNotEmpty(positionList)) {
					//CRMApiUtils.getCRMServiceApi().updateServiceStationLonAndLatInfos(companyChannel, positionList);
				}
				// 返回客户
				ParameterTool.writeSuccessResponse(response);
				return null;


			} else if (companyChannel.equals(CRMServiceConst.DCEC) || companyChannel.equals(CRMServiceConst.XCEC)) { // DCEC渠道和XCEC渠道

				List<Map<String, Object>> positionList = new ArrayList<>();
				// 1、获取当前企业编号
				CompanyT company = companyTDao.getCompanyInfoByCompanyNo(companyChannel);
				List<Map<String, Object>> serviceStationList = JSONArray
						.fromObject(httpMap.get(CRMServiceConst.CRM_REQUEST_PARAMS).toString());

				com.alibaba.fastjson.JSONObject oneTwoStation = splitStation(serviceStationList);
				List<Map<String, Object>> oneStation = (List<Map<String, Object>>)oneTwoStation.get("oneStation");
				List<Map<String, Object>> twoStation = (List<Map<String, Object>>)oneTwoStation.get("twoStation");
				Map<String, Long> stationIdAndStationNoMap = new HashMap<>();

				// 2、判断接口服务商数据是否为空
				if (CollectionUtils.isNotEmpty(oneStation)) {
					List<String> stationNoList = new ArrayList<>();
					for (Map<String, Object> map : oneStation) {
						String stationName = MapUtils.getString(map, "stationName");
						String stationNo = MapUtils.getString(map, "stationNo");
						String requstStatus = MapUtils.getString(map, "requstStatus");
						// 3、判断数据列表是否有重复数据（服务站编号+操作状态标示）
						if (stationNoList.contains(stationNo + requstStatus)) {
							crmLogService.saveCrmErrorLog(companyChannel, apiName, JSONObject.fromObject(map).toString(),
									"列表中服务商操作重复" + stationNo);
							continue;
						} else {
							stationNoList.add(stationNo + requstStatus);
						}
						// 4、如果服务站名字或者编号为空，忽略此条数据，并记录到错误日志表
						if (StringUtils.isEmpty(stationName) || StringUtils.isEmpty(stationNo)) {
							crmLogService.saveCrmErrorLog(companyChannel, apiName, JsonUtils.toJsonString(map),
									"服务商名称/编号为空");
							continue;
						}
						Map<String, Object> queryMap = new HashMap<>(2);
						queryMap.put("companyId", company.getId());
						queryMap.put("stationNo", stationNo);
						// 5、通过服务商编号和企业编号查询服务站授权信息表
						List<Map<String, Object>> ssRepairList = ssRepairTDao
								.getSSRepairTByServiceStationNoCompanyID(queryMap);
						// 6、通过服务商名称查询服务商信息
						List<ServiceStationT> serviceStationTList = serviceStationDao
								.getServiceStationListByStationName(stationName);
						// 授权关系为空
						if (CollectionUtils.isEmpty(ssRepairList)) {
							if (requstStatus.equals("2")) {
								// 删除原编号管辖信息
								deletePositionUserServiceStation(company.getId(), stationNo);
								crmLogService.saveCrmErrorLog(companyChannel, apiName, JsonUtils.toJsonString(map),
										"未查询到服务商授权数据，无法删除");
								continue;
							}
							// 服务商主数据为空
							if (CollectionUtils.isEmpty(serviceStationTList)) {
								// 转换为数据库MAP -- DCEC需求，新增requstStatus字段：操作状态（增加1；删除2；修改3;冻结 4；解冻 5）	20210510
								Map<String, Object> serviceStationInfoMap = new HashMap<>();
								if (companyChannel.equals(CRMServiceConst.DCEC) ){
									serviceStationInfoMap = getDCECServiceStationMap(map, null, company);
								} else {
									serviceStationInfoMap = getXCECServiceStationMap(map, null, company);
								}
								// 获取地址经纬等信息
								getDCECAndXCECAddressInfo(serviceStationInfoMap, positionList, companyChannel);
								// 将数据存入数据库
								int saveServiceStationResult = crmServiceDao
										.insertServiceStationInfo(serviceStationInfoMap);
								if (saveServiceStationResult > 0) {
									Long serviceStationId = MapUtils.getLong(serviceStationInfoMap, "ssid");

									stationIdAndStationNoMap.put(MapUtils.getString(map, "stationNo"), serviceStationId);

									serviceStationInfoMap.put("CompanyID", company.getId());
									serviceStationInfoMap.put("ServiceStationID", serviceStationId);
									// 维护授权关系
									saveSSRepair(serviceStationInfoMap, SSRepairOperation.SAVE);
									//saveSSHasCompany(MapUtils.getString(map,"vehicleCompanies"),company.getId(),serviceStationId);
									//saveSSHasServiceType(MapUtils.getString(map,"serviceType"),company.getId(),serviceStationId);
									//saveSSHasVehicleType(MapUtils.getString(map,"vehicleType"),company.getId(),serviceStationId);
									//saveSSHasSMN(MapUtils.getString(map,"authorizedMode"),company.getId(),serviceStationId);

									// 根据插入表返回id编辑服务站序号
									Map<String, Object> updateMap = new HashedMap<String, Object>();
									String cStationNo = String.format("C" + "%05d", serviceStationId);
									updateMap.put("StationNo", cStationNo);
									updateMap.put("id", serviceStationId);
									crmServiceDao.updateStationInfoByPrimaryKey(updateMap);
								} else {
									crmLogService.saveCrmErrorLog(companyChannel, apiName, JsonUtils.toJsonString(map),
											"服务商信息保存失败");
								}
							} else {
								// 理论上，同名服务商有且仅有一家
								ServiceStationT serviceStationT = serviceStationTList.get(0);//这里可能有多条，所以在上线前把所有数据放在excel中对比
								// 先删除该服务商授权关系，预防同服务商存在不同编号的多条授权
								ssRepairTDao.deleteSSRepairTByID(serviceStationT.getId(), company.getId());
								// 2021-12-10新增,删除这个服务站对应管辖关系
								deletePositionUserServiceStationId(company.getId(), serviceStationT.getId());
								// 删除编号管辖信息
								deletePositionUserServiceStation(company.getId(), stationNo);//这个根据入参的鉴定号删除也没问题，但少了一种根据上边服务站的id删除场景（如果不这么删除PositionUserServiceStation_T可能会存在同一个服务站id对应多个不同的鉴定号），
								// 转换为数据库MAP -- DCEC需求，新增requstStatus字段：操作状态（增加1；删除2；修改3;冻结 4；解冻 5）	20210510
								Map<String, Object> serviceStationInfoMap = new HashMap<>();
								if (companyChannel.equals(CRMServiceConst.DCEC) ){
									serviceStationInfoMap = getDCECServiceStationMap(map, null, company);
								} else {
									serviceStationInfoMap = getXCECServiceStationMap(map, null, company);
								}
								// 获取地址经纬等信息
								getDCECAndXCECAddressInfo(serviceStationInfoMap, positionList, companyChannel);
								serviceStationInfoMap.put("CompanyID", company.getId());
								serviceStationInfoMap.put("ServiceStationID", serviceStationT.getId());
								serviceStationInfoMap.put("id", serviceStationT.getId());

								stationIdAndStationNoMap.put(MapUtils.getString(map, "stationNo"), serviceStationT.getId());

								// 更新服务商信息
								crmServiceDao.updateStationInfoByPrimaryKey(serviceStationInfoMap);
								// 插入服务商授权信息
								saveSSRepair(serviceStationInfoMap, SSRepairOperation.SAVE);
								//saveSSHasCompany(MapUtils.getString(map,"vehicleCompanies"),company.getId(),serviceStationT.getId());
								//saveSSHasServiceType(MapUtils.getString(map,"serviceType"),company.getId(),serviceStationT.getId());
								//saveSSHasVehicleType(MapUtils.getString(map,"vehicleType"),company.getId(),serviceStationT.getId());
								//saveSSHasSMN(MapUtils.getString(map,"authorizedMode"),company.getId(),serviceStationT.getId());
							}
						} else {
							// 授权信息不为空
							Map<String, Object> ssRepairMap = ssRepairList.get(0);//可能存在大于1条的情况，用excel列出来让SF人员排查，保证1对1关系
							Long ssStationId = MapUtils.getLong(ssRepairMap, "ServiceStationID");
							// 当操作为删除时
							if (requstStatus.equals("2")) {
								// 删除授权信息
								ssRepairTDao.deleteSSRepairTByID(ssStationId, company.getId());
								// 删除编号管辖信息
								deletePositionUserServiceStation(company.getId(), stationNo);
								continue;
							}
							// 非删除操作，当服务商信息为空
							if (CollectionUtils.isEmpty(serviceStationTList)) {
								// 转换为数据库MAP -- DCEC需求，新增requstStatus字段：操作状态（增加1；删除2；修改3;冻结 4；解冻 5）	20210510
								Map<String, Object> serviceStationInfoMap = new HashMap<>();
								if (companyChannel.equals(CRMServiceConst.DCEC) ){
									serviceStationInfoMap = getDCECServiceStationMap(map, null, company);
								} else {
									serviceStationInfoMap = getXCECServiceStationMap(map, null, company);
								}
								// 获取地址经纬等信息
								getDCECAndXCECAddressInfo(serviceStationInfoMap, positionList, companyChannel);
								serviceStationInfoMap.put("CompanyID", company.getId());
								serviceStationInfoMap.put("ServiceStationID", ssStationId);
								serviceStationInfoMap.put("id", ssStationId);

								stationIdAndStationNoMap.put(MapUtils.getString(map, "stationNo"), ssStationId);

								// 更新服务商信息
								serviceStationInfoMap.put("SSRepairId", MapUtils.getLong(ssRepairMap, "ID"));// 根据鉴定号查到授权数据后，通过授权表中服务站id更新服务站表，服务站id和鉴定号都不变所以关系关系表不用更新
								crmServiceDao.updateStationInfoByPrimaryKey(serviceStationInfoMap);
								saveSSRepair(serviceStationInfoMap, SSRepairOperation.UPDATE);//更新授权表也没问题，但更相信前和更新后授权的主要数据无变化，
								//saveSSHasCompany(MapUtils.getString(map,"vehicleCompanies"),company.getId(),ssStationId);
								//saveSSHasServiceType(MapUtils.getString(map,"serviceType"),company.getId(),ssStationId);
								//saveSSHasVehicleType(MapUtils.getString(map,"vehicleType"),company.getId(),ssStationId);
								//saveSSHasSMN(MapUtils.getString(map,"authorizedMode"),company.getId(),ssStationId);
							} else {
								// 服务商数据不为空，判断是否是授权服务商
								ServiceStationT serviceStationT = serviceStationTList.get(0);
								// 当前服务商为授权服务商，更新所有数据
								if (ssStationId.equals(serviceStationT.getId())) {
									// 转换为数据库MAP -- DCEC需求，新增requstStatus字段：操作状态（增加1；删除2；修改3;冻结 4；解冻 5）	20210510
									Map<String, Object> serviceStationInfoMap = new HashMap<>();
									if (companyChannel.equals(CRMServiceConst.DCEC) ){
										serviceStationInfoMap = getDCECServiceStationMap(map, null, company);
									} else {
										serviceStationInfoMap = getXCECServiceStationMap(map, null, company);
									}
									// 获取地址经纬等信息
									getDCECAndXCECAddressInfo(serviceStationInfoMap, positionList, companyChannel);
									serviceStationInfoMap.put("CompanyID", company.getId());
									serviceStationInfoMap.put("ServiceStationID", ssStationId);
									serviceStationInfoMap.put("id", ssStationId);

									stationIdAndStationNoMap.put(MapUtils.getString(map, "stationNo"), ssStationId);

									// 更新服务商信息
									crmServiceDao.updateStationInfoByPrimaryKey(serviceStationInfoMap);
									serviceStationInfoMap.put("SSRepairId", MapUtils.getLong(ssRepairMap, "ID"));
									saveSSRepair(serviceStationInfoMap, SSRepairOperation.UPDATE);
									//saveSSHasCompany(MapUtils.getString(map,"vehicleCompanies"),company.getId(),ssStationId);
									//saveSSHasServiceType(MapUtils.getString(map,"serviceType"),company.getId(),ssStationId);
									//saveSSHasVehicleType(MapUtils.getString(map,"vehicleType"),company.getId(),ssStationId);
									//saveSSHasSMN(MapUtils.getString(map,"authorizedMode"),company.getId(),ssStationId);
								} else {
									// 当前服务商非授权服务商，记录异常信息
									crmLogService.saveCrmErrorLog(companyChannel, apiName, JsonUtils.toJsonString(map),
											"服务商信息与数据库信息发生冲突，无法处理");
								}
							}
						}
					}
				} else {
					if (CollectionUtils.isNotEmpty(twoStation)) {
						addTwoStation(company, twoStation, stationIdAndStationNoMap, positionList);
					} else {
						// 同步服务商数据为空
						crmLogService.saveCrmErrorLog(companyChannel, apiName, JsonUtils.toJsonString(httpMap),
								"服务站信息同步失败，服务商数据为空");
						ParameterTool.writeResponse(response, 1, "同步失败，服务商信息为空");
						return null;
					}
				}

				// 服务商地址信息同步
				if (CollectionUtils.isNotEmpty(positionList)) {
					CRMApiUtils.getCRMServiceApi().updateServiceStationLonAndLatInfos(companyChannel, positionList);
				}
				// 返回客户
				ParameterTool.writeSuccessResponse(response);
				return null;

			} else if (companyChannel.equals(CRMServiceConst.CCEC)) {
				List<Map<String, Object>> positionList = new ArrayList<>();
				CompanyT company = companyTDao.getCompanyInfoByCompanyNo(companyChannel);
				List<Map<String, Object>> serviceStationList = JSONArray
						.fromObject(httpMap.get(CRMServiceConst.CRM_REQUEST_PARAMS).toString());
				if (CollectionUtils.isNotEmpty(serviceStationList)) {
					List<String> stationNoList = new ArrayList<>();
					for (Map<String, Object> map : serviceStationList) {
						String stationName = MapUtils.getString(map, "stationName");
						String stationNo = MapUtils.getString(map, "stationNo");
						String requstStatus = MapUtils.getString(map, "requstStatus");
						if (stationNoList.contains(stationNo + requstStatus)) {
							crmLogService.saveCrmErrorLog(companyChannel, apiName, JsonUtils.toJsonString(map),
									"列表中服务商操作重复" + stationNo);
							continue;
						} else {
							stationNoList.add(stationNo + requstStatus);
						}
						if (StringUtils.isEmpty(stationName) || StringUtils.isEmpty(stationNo)) {
							crmLogService.saveCrmErrorLog(companyChannel, apiName, JsonUtils.toJsonString(map),
									"服务商名称/编号为空");
							continue;
						}
						Map<String, Object> queryMap = new HashMap<>(2);
						queryMap.put("companyId", company.getId());
						queryMap.put("stationNo", stationNo);
						List<Map<String, Object>> ssRepairList = ssRepairTDao
								.getSSRepairTByServiceStationNoCompanyID(queryMap);
						// 通过服务商名称查询服务商信息
						List<ServiceStationT> serviceStationTList = serviceStationDao
								.getServiceStationListByStationName(stationName);
						// 授权关系为空
						if (CollectionUtils.isEmpty(ssRepairList)) {
							if (requstStatus.equals("2")) {
								// 删除原编号管辖信息
								deletePositionUserServiceStation(company.getId(), stationNo);
								crmLogService.saveCrmErrorLog(companyChannel, apiName, JsonUtils.toJsonString(map),
										"未查询到服务商授权数据，无法删除");
								continue;
							}
							// 服务商主数据为空
							if (CollectionUtils.isEmpty(serviceStationTList)) {
								// 转换为数据库MAP
								Map<String, Object> serviceStationInfoMap = geCCECServiceStationMap(map, null, company);
								// 获取地址经纬等信息
								getAddressInfo(serviceStationInfoMap, positionList);
								// 将数据存入数据库
								int saveServiceStationResult = crmServiceDao
										.insertServiceStationInfo(serviceStationInfoMap);
								if (saveServiceStationResult > 0) {
									Long serviceStationId = MapUtils.getLong(serviceStationInfoMap, "ssid");
									serviceStationInfoMap.put("CompanyID", company.getId());
									serviceStationInfoMap.put("ServiceStationID", serviceStationId);
									// 维护授权关系
									saveSSRepair(serviceStationInfoMap, SSRepairOperation.SAVE);
									saveSSHasSMN(MapUtils.getString(map, "authorizedMode"), company.getId(),
											serviceStationId);

									// 根据插入表返回id编辑服务站序号
									Map<String, Object> updateMap = new HashedMap<String, Object>();
									String cStationNo = String.format("C" + "%05d", serviceStationId);
									updateMap.put("StationNo", cStationNo);
									updateMap.put("id", serviceStationId);
									crmServiceDao.updateStationInfoByPrimaryKey(updateMap);
								} else {
									crmLogService.saveCrmErrorLog(companyChannel, apiName, JsonUtils.toJsonString(map),
											"服务商信息保存失败");
								}
							} else {
								// 理论上，同名服务商有且仅有一家
								ServiceStationT serviceStationT = serviceStationTList.get(0);
								// 先删除该服务商授权关系，预防同服务商存在不同编号的多条授权
								ssRepairTDao.deleteSSRepairTByID(serviceStationT.getId(), company.getId());
								// 删除原编号管辖信息
								deletePositionUserServiceStation(company.getId(), stationNo);
								Map<String, Object> serviceStationInfoMap = geCCECServiceStationMap(map,
										serviceStationT.getId(), company);
								// 获取地址经纬等信息
								getAddressInfo(serviceStationInfoMap, positionList);
								serviceStationInfoMap.put("CompanyID", company.getId());
								serviceStationInfoMap.put("ServiceStationID", serviceStationT.getId());
								serviceStationInfoMap.put("id", serviceStationT.getId());
								// 更新服务商信息
								crmServiceDao.updateStationInfoByPrimaryKey(serviceStationInfoMap);
								// 插入服务商授权信息
								saveSSRepair(serviceStationInfoMap, SSRepairOperation.SAVE);
								//saveSSHasCompany(MapUtils.getString(map,"vehicleCompanies"),company.getId(),serviceStationT.getId());
								//saveSSHasServiceType(MapUtils.getString(map,"serviceType"),company.getId(),serviceStationT.getId());
								//saveSSHasVehicleType(MapUtils.getString(map,"vehicleType"),company.getId(),serviceStationT.getId());
								saveSSHasSMN(MapUtils.getString(map, "authorizedMode"), company.getId(),
										serviceStationT.getId());
							}
						} else {
							// 授权信息不为空
							Map<String, Object> ssRepairMap = ssRepairList.get(0);
							Long ssStationId = MapUtils.getLong(ssRepairMap, "ServiceStationID");
							// 当操作为删除时
							if (requstStatus.equals("2")) {
								// 删除授权信息
								ssRepairTDao.deleteSSRepairTByID(ssStationId, company.getId());
								// 删除编号管辖信息
								deletePositionUserServiceStation(company.getId(), stationNo);
								continue;
							}
							// 非删除操作，当服务商信息为空
							if (CollectionUtils.isEmpty(serviceStationTList)) {
								// 将绑定授权关系的服务商数据更新
								Map<String, Object> serviceStationInfoMap = geCCECServiceStationMap(map, null, company);
								// 获取地址经纬等信息
								getAddressInfo(serviceStationInfoMap, positionList);
								serviceStationInfoMap.put("CompanyID", company.getId());
								serviceStationInfoMap.put("ServiceStationID", ssStationId);
								serviceStationInfoMap.put("id", ssStationId);
								// 更新服务商信息
								serviceStationInfoMap.put("SSRepairId", MapUtils.getLong(ssRepairMap, "ID"));
								crmServiceDao.updateStationInfoByPrimaryKey(serviceStationInfoMap);
								saveSSRepair(serviceStationInfoMap, SSRepairOperation.UPDATE);
								//saveSSHasCompany(MapUtils.getString(map,"vehicleCompanies"),company.getId(),ssStationId);
								//saveSSHasServiceType(MapUtils.getString(map,"serviceType"),company.getId(),ssStationId);
								//saveSSHasVehicleType(MapUtils.getString(map,"vehicleType"),company.getId(),ssStationId);
								saveSSHasSMN(MapUtils.getString(map, "authorizedMode"), company.getId(), ssStationId);
							} else {
								// 服务商数据不为空，判断是否是授权服务商
								ServiceStationT serviceStationT = serviceStationTList.get(0);
								// 当前服务商为授权服务商，更新所有数据
								if (ssStationId.equals(serviceStationT.getId())) {
									// 将绑定授权关系的服务商数据更新
									Map<String, Object> serviceStationInfoMap = geCCECServiceStationMap(map,
											serviceStationT.getId(), company);
									// 获取地址经纬等信息
									getAddressInfo(serviceStationInfoMap, positionList);
									serviceStationInfoMap.put("CompanyID", company.getId());
									serviceStationInfoMap.put("ServiceStationID", ssStationId);
									serviceStationInfoMap.put("id", ssStationId);
									// 更新服务商信息
									crmServiceDao.updateStationInfoByPrimaryKey(serviceStationInfoMap);
									serviceStationInfoMap.put("SSRepairId", MapUtils.getLong(ssRepairMap, "ID"));
									saveSSRepair(serviceStationInfoMap, SSRepairOperation.UPDATE);
									//saveSSHasCompany(MapUtils.getString(map,"vehicleCompanies"),company.getId(),ssStationId);
									//saveSSHasServiceType(MapUtils.getString(map,"serviceType"),company.getId(),ssStationId);
									//saveSSHasVehicleType(MapUtils.getString(map,"vehicleType"),company.getId(),ssStationId);
									saveSSHasSMN(MapUtils.getString(map, "authorizedMode"), company.getId(), ssStationId);
								} else {
									// 当前服务商非授权服务商，记录异常信息
									crmLogService.saveCrmErrorLog(companyChannel, apiName, JsonUtils.toJsonString(map),
											"服务商信息与数据库信息发生冲突，无法处理");
								}
							}
						}
					}
				} else {
					// 同步服务商数据为空
					crmLogService.saveCrmErrorLog(companyChannel, apiName, JsonUtils.toJsonString(httpMap),
							"服务站信息同步失败，服务商数据为空");
					ParameterTool.writeResponse(response, 1, "同步失败，服务商信息为空");
					return null;
				}

				// 服务商地址信息同步,CRM开发说不需要
				/*if (CollectionUtils.isNotEmpty(positionList)) {
					CRMApiUtils.getCRMServiceApi().updateServiceStationLonAndLatInfos(companyChannel, positionList);
				}*/
				// 返回客户
				ParameterTool.writeSuccessResponse(response);
				return null;
			} else // 未支持企业编号
			{
				JSONObject jsonObject = new JSONObject();
				JSONObject jsonData = new JSONObject();
				jsonObject.put("status", 1);
				jsonObject.put("msg", "企业编号不存在");
				jsonObject.put("data", jsonData);

				ParameterTool.writeResponse(response, jsonObject.toString());
				return null;
			}
		} catch (Exception e) {
			LOG.error(e.getMessage(),e);
			String msg = "{\"status\": -99,\"msg\": \"未知错误\"}";
			ParameterTool.writeResponse(response, msg);
		}finally {
			//释放锁
			redisClientUtils.delkey(key);
		}
		return null;
	}

	 /**
	  * @description: dcec渠道把一网和二网拆开
	  * @param:
	  * @return:
	  * @exception:
	  * @author: shiliqiang
	  * @company: CTY Technology Co.,Ltd
	  * @since: 2022/5/19 14:07
	  * @version: V1.0
	  */
	private com.alibaba.fastjson.JSONObject splitStation(List<Map<String, Object>> serviceStationList) {
		List<Map<String, Object>> oneStationList = new ArrayList<>();
		List<Map<String, Object>> twoStationList = new ArrayList<>();
		com.alibaba.fastjson.JSONObject jsonObj = new com.alibaba.fastjson.JSONObject();
		for (Map<String, Object> map : serviceStationList) {
			Object obj = map.get("fatherStationNo");
			// fatherStationNo为空是一网，否则是二网
			if (obj == null || StringUtils.isEmpty(obj.toString())) {
				oneStationList.add(map);
			} else {
				twoStationList.add(map);
			}
		}
		jsonObj.put("oneStation", oneStationList);
		jsonObj.put("twoStation", twoStationList);
		return jsonObj;
	}

	private void addTwoStation(CompanyT company, List<Map<String, Object>> twoStationList, Map<String, Long> stationIdAndStationNoMap, List<Map<String, Object>> positionList) {
		List<String> stationNoList = new ArrayList<>();
		String apiName = "syncStationInfo";
		//List<Map<String, Object>> positionList = new ArrayList<>();

		for (Map<String, Object> map : twoStationList) {
			String stationName = MapUtils.getString(map, "stationName");
			String stationNo = MapUtils.getString(map, "stationNo");
			String fatherStationNo = MapUtils.getString(map, "fatherStationNo");

			// 如果服务站名字或者编号为空，忽略此条数据，并记录到错误日志表
			if (StringUtils.isEmpty(stationName) || StringUtils.isEmpty(stationNo)) {
				crmLogService.saveCrmErrorLog(stationNo, apiName, JsonUtils.toJsonString(map),
						"服务商名称/编号为空");
				continue;
			}
			if (StringUtils.isEmpty(fatherStationNo)) {
				crmLogService.saveCrmErrorLog(stationNo, apiName, JsonUtils.toJsonString(map),
						"服务商的一网鉴定号为空");
				continue;
			}
			// 如果是二网则能查询到一网的鉴定号
			Long fatherStationId = MapUtils.getLong(stationIdAndStationNoMap, fatherStationNo);
			//fatherStationId等于null时代表SF同步的一网数据，未同步二网
			if (fatherStationId == null) {
				ServiceStationT serviceStation = serviceStationDao.getServiceStationByStationNo(company.getId(),fatherStationNo);
				if (serviceStation != null) {
					fatherStationId = serviceStation.getId();
					//stationIdAndStationNoMap.put(fatherStationNo, serviceStation.getId());
				}
			}

			List<ServiceStationT> serviceStationTList = serviceStationDao.getServiceStationListByStationNameTwo(stationName);
			if (serviceStationTList == null || serviceStationTList.size() < 1) {
				// 把鉴定号一致的删除(同一个渠道下鉴定号不能重复)
				List<SSRepairT> ssRepairList = ssRepairTDao.queryAuthByStationNo(company.getId(), stationNo);
				if (ssRepairList != null && ssRepairList.size() > 0) {
					ssRepairTDao.deleteSSRepairTByStationNo(stationNo, company.getId());
				}

				// 做新增服务站信息、授权信息、一网服务站和二网服务站信息
				Map<String, Object> serviceStationInfoMap = new HashMap<>();
				serviceStationInfoMap = getDCECServiceStationMap(map, null, company);

				// 获取地址经纬等信息
				getDCECAndXCECAddressInfo(serviceStationInfoMap, positionList, company.getCompanyNo());
				// 将数据存入数据库
				int saveServiceStationResult = crmServiceDao.insertServiceStationInfo(serviceStationInfoMap);
				if (saveServiceStationResult > 0) {
					Long serviceStationId = MapUtils.getLong(serviceStationInfoMap, "ssid");
					// 空为一网，非空为二网,RelationType为空/null/1表示一网，2表示二网
//					if (!StringUtils.isEmpty(fatherStationNo)) {
//
//					}
					List<Map<String,Object>> relationMap = crmServiceDao.queryServiceStationRelationInfo(saveServiceStationRelationInfo(fatherStationId, serviceStationId));
					if (relationMap == null || relationMap.size() < 1) {
						// 把一网二网关系插入表中
						crmServiceDao.insertServiceStationRelationInfo(saveServiceStationRelationInfo(fatherStationId, serviceStationId));
					} else {
						crmServiceDao.updateServiceStationRelationInfo(saveServiceStationRelationInfo(fatherStationId, serviceStationId));
					}

					serviceStationInfoMap.put("CompanyID", company.getId());
					serviceStationInfoMap.put("ServiceStationID", serviceStationId);
					// 维护授权关系
					saveSSRepair(serviceStationInfoMap, SSRepairOperation.SAVE);
					// 根据插入表返回id编辑服务站序号
					Map<String, Object> updateMap = new HashedMap<String, Object>();
					String cStationNo = String.format("C" + "%05d", serviceStationId);
					updateMap.put("StationNo", cStationNo);
					updateMap.put("id", serviceStationId);
					crmServiceDao.updateStationInfoByPrimaryKey(updateMap);
				} else {
					crmLogService.saveCrmErrorLog(company.getCompanyNo(), apiName, JsonUtils.toJsonString(map),
							"服务商信息保存失败");
				}

			} else {
				//List<SSRepairT> ssRepairList = ssRepairTDao.queryAuthByStationId(serviceStationTList.get(0).getId(), company.getId(), stationNo);
				List<SSRepairT> ssRepairList = ssRepairTDao.queryAuthByStationNo(company.getId(), stationNo);
				if (ssRepairList != null && ssRepairList.size() > 0) {
					ssRepairTDao.deleteSSRepairTByStationNo(stationNo, company.getId());
				}
				//服务站做更新，授权表做新增
				ServiceStationT serviceStationT = serviceStationTList.get(0);
				// 当前服务商为授权服务商，更新所有数据
				Map<String, Object> serviceStationInfoMap = new HashMap<>();
				serviceStationInfoMap = getDCECServiceStationMap(map, null, company);

				// 获取地址经纬等信息
				getDCECAndXCECAddressInfo(serviceStationInfoMap, positionList, company.getCompanyNo());
				serviceStationInfoMap.put("CompanyID", company.getId());
				serviceStationInfoMap.put("ServiceStationID", serviceStationT.getId());
				serviceStationInfoMap.put("id", serviceStationT.getId());

				// 更新服务商信息
				crmServiceDao.updateStationInfoByPrimaryKey(serviceStationInfoMap);

				List<Map<String,Object>> relationMap = crmServiceDao.queryServiceStationRelationInfo(saveServiceStationRelationInfo(fatherStationId, serviceStationT.getId()));
				if (relationMap == null || relationMap.size() < 1) {
					// 把一网二网关系插入表中
					crmServiceDao.insertServiceStationRelationInfo(saveServiceStationRelationInfo(fatherStationId, serviceStationT.getId()));
				} else {
					crmServiceDao.updateServiceStationRelationInfo(saveServiceStationRelationInfo(fatherStationId, serviceStationT.getId()));
				}

				saveSSRepair(serviceStationInfoMap, SSRepairOperation.SAVE);

			}
		}
	}
	private Map<String, Object> saveServiceStationRelationInfo(Long fatherStationId, Long stationId) {
		Map<String, Object> map = new HashMap<>();
		map.put("ChildID", stationId);
		map.put("ParentID", fatherStationId);
		map.put("Flag", 0);
		map.put("CreateTime", LocalTimeUtil.getRealCurrentTime());
		map.put("UpdateTime", LocalTimeUtil.getRealCurrentTime());
		return map;
	}


	private void saveDealersInfo(Map<String, Object> map, Long serviceStationId, Long companyId) {
		LOG.info(String.format("保存Dealer-Info map:%s  serviceStationId:%s   companyId:%s ", map, serviceStationId, companyId));

		// 当前渠道与服务站是否已存在数据
		Map<String, Object> dealerInfoMap = crmServiceDao.getDealerInfoByStationIdAndCompanyId(serviceStationId, companyId);

		Map<String, Object> dealerInfo = new HashMap<>();
		dealerInfo.put("AuthModel", 		MapUtils.getString(map, "authModel"));
		dealerInfo.put("BranchName", 		MapUtils.getString(map, "branchName"));
		dealerInfo.put("AuthMarket", 		MapUtils.getString(map, "authMarket"));
		dealerInfo.put("AuthLevel", 		MapUtils.getString(map, "authLevel"));
		dealerInfo.put("GradedStatus", 		MapUtils.getString(map, "identity"));
		dealerInfo.put("Region",         	MapUtils.getString(map, "area"));
		dealerInfo.put("ServiceStationId", serviceStationId);
		dealerInfo.put("CompanyId", companyId);

		if(MapUtils.isNotEmpty(dealerInfoMap)) {
			dealerInfo.put("ID", MapUtils.getLong(dealerInfoMap, "id"));
			dealerInfo.put("UpdateTime", LocalTimeUtil.getCurrentTime());
			crmServiceDao.updateDealerInfoSelectiveById(dealerInfo);
		}else {
			dealerInfo.put("CreateTime", LocalTimeUtil.getCurrentTime());
			crmServiceDao.insertDealerInfoSelective(dealerInfo);
		}

	}




	private void deletePositionUserServiceStation(Long companyId, String serviceStationNo) {
		Map<String, Object> updateMap = new HashMap<>(4);
		updateMap.put("Deleter", companyId);
		updateMap.put("DeleteTime", LocalTimeUtil.getRealCurrentTime());
		updateMap.put("ServiceStationNo", serviceStationNo);
		updateMap.put("CompanyID", companyId);
		crmServiceDao.deletePositionUserServiceStationByChannelAndStationNo(updateMap);
	}

	private void deletePositionUserServiceStationId(Long companyId, long serviceStationId) {
		Map<String, Object> updateMap = new HashMap<>(4);
		updateMap.put("Deleter", companyId);
		updateMap.put("DeleteTime", LocalTimeUtil.getRealCurrentTime());
		updateMap.put("ServiceStationId", serviceStationId);
		updateMap.put("CompanyID", companyId);
		crmServiceDao.deletePositionUserServiceStationByChannelAndStationId(updateMap);
	}

	private void getAddressInfo(Map<String, Object> serviceStationMap, List<Map<String, Object>> positionList) {
		String address = MapUtils.getString(serviceStationMap, "Address", "");
		Map<String, Object> addressMap = AddressConverter.getAddressInfo(address);
		if (MapUtils.isEmpty(addressMap)) {
			crmLogService.saveCrmErrorLog("CCI", "syncStationInfo", JsonUtils.toJsonString(serviceStationMap),
					"地址信息映射失败");
			if(!serviceStationMap.containsKey("PositionLat") || StringUtils.isBlank(MapUtils.getString(serviceStationMap, "PositionLat"))
			|| !serviceStationMap.containsKey("PositionLon") || StringUtils.isBlank(MapUtils.getString(serviceStationMap, "PositionLon"))){
				addressMap = AddressConverter.getAddressInfo("北京市东城区天安门");
			}

		}
		if (MapUtils.isNotEmpty(addressMap)) {
			String city = MapUtils.getString(addressMap, "city", "");
			if (city.equals("[]")) {
				city = "";
			}
			String area = MapUtils.getString(addressMap, "area", "");
			if (area.equals("[]")) {
				area = "";
			}
			serviceStationMap.put("Province", MapUtils.getString(addressMap, "province", ""));
			serviceStationMap.put("City", city);
			serviceStationMap.put("Area", area);
			serviceStationMap.put("PositionLat", MapUtils.getString(addressMap, "latitude", ""));
			serviceStationMap.put("PositionLon", MapUtils.getString(addressMap, "longitude", ""));

		}
		Map<String, Object> positionMap = new HashMap<>(5);
		positionMap.put("stationNo", MapUtils.getString(serviceStationMap, "BusinessNo", ""));
		positionMap.put("address", address);
		positionMap.put("positionLat", MapUtils.getDouble(serviceStationMap, "PositionLat", 0.0));
		positionMap.put("positionLon", MapUtils.getDouble(serviceStationMap, "PositionLon", 0.0));
		positionMap.put("provice", MapUtils.getString(serviceStationMap, "Province", ""));
		positionMap.put("city", MapUtils.getString(serviceStationMap, "City", ""));
		positionList.add(positionMap);
	}

	private void getDCECAndXCECAddressInfo(Map<String, Object> serviceStationMap,
										   List<Map<String, Object>> positionList, String companyChannel) {
		String address = MapUtils.getString(serviceStationMap, "Address", "");
		Map<String, Object> addressMap = AddressConverter.getAddressInfo(address);
		if (MapUtils.isEmpty(addressMap)) {
			crmLogService.saveCrmErrorLog(companyChannel, "syncStationInfo", JsonUtils.toJsonString(serviceStationMap),
					"地址信息映射失败");
			if(!serviceStationMap.containsKey("PositionLat") || StringUtils.isBlank(MapUtils.getString(serviceStationMap, "PositionLat"))
					|| !serviceStationMap.containsKey("PositionLon") || StringUtils.isBlank(MapUtils.getString(serviceStationMap, "PositionLon"))){
				addressMap = AddressConverter.getAddressInfo("北京市东城区天安门");
			}
		}
		if (MapUtils.isNotEmpty(addressMap)) {
			serviceStationMap.put("Province", MapUtils.getString(addressMap, "province", ""));
			serviceStationMap.put("City", MapUtils.getString(addressMap, "city", ""));
			serviceStationMap.put("Area", MapUtils.getString(addressMap, "area", ""));
			serviceStationMap.put("PositionLat", MapUtils.getString(addressMap, "latitude", ""));
			serviceStationMap.put("PositionLon", MapUtils.getString(addressMap, "longitude", ""));
		}
		Map<String, Object> positionMap = new HashMap<>(5);
		positionMap.put("stationNo", MapUtils.getString(serviceStationMap, "BusinessNo", ""));
		positionMap.put("address", address);
		if (companyChannel.equals(CRMServiceConst.DCEC)) {
			positionMap.put("positionLat", MapUtils.getDouble(serviceStationMap, "PositionLon", 0.0));
			positionMap.put("positionLon", MapUtils.getDouble(serviceStationMap, "PositionLat", 0.0));
			if (MapUtils.getDouble(serviceStationMap, "PositionLon") < 60) { // APP操作同步，非重传，参数需要座处理
				serviceStationMap.put("PositionLon", positionMap.get("positionLon"));
				serviceStationMap.put("PositionLat", positionMap.get("positionLat"));
			}
		} else {
			positionMap.put("positionLat", MapUtils.getDouble(serviceStationMap, "PositionLat", 0.0));
			positionMap.put("positionLon", MapUtils.getDouble(serviceStationMap, "PositionLon", 0.0));
			positionMap.put("hotLineOne", MapUtils.getString(serviceStationMap, "Telephone", ""));
			positionMap.put("hotLineTwo", MapUtils.getString(serviceStationMap, "Phone", ""));
			positionMap.put("detailedAddress", address);
		}
		positionMap.put("provice", MapUtils.getString(serviceStationMap, "Province", ""));
		positionMap.put("city", MapUtils.getString(serviceStationMap, "City", ""));
		positionList.add(positionMap);
	}

	private Map<String, Object> getDBUServiceStationMap(Map<String, Object> map, Long serviceStationId,
														CompanyT companyT) {
		Map<String, Object> serviceStationInfoMap = new HashMap<>();
		if (null != serviceStationId) {
			serviceStationInfoMap.put("ServiceStationID", serviceStationId);
		}
		// 服务商表ServiceStation_T
		serviceStationInfoMap.put("StationName", MapUtils.getString(map, "stationName"));
		serviceStationInfoMap.put("Abbreviation", MapUtils.getString(map, "shortName"));
		serviceStationInfoMap.put("Province", MapUtils.getString(map, "province"));
		serviceStationInfoMap.put("City", MapUtils.getString(map, "city"));
		serviceStationInfoMap.put("Area", MapUtils.getString(map, "area"));
		serviceStationInfoMap.put("Address", MapUtils.getString(map, "address"));
		serviceStationInfoMap.put("Contact", MapUtils.getString(map, "contact"));
		serviceStationInfoMap.put("Telephone", MapUtils.getString(map, "telephone"));
		serviceStationInfoMap.put("Phone", MapUtils.getString(map, "phone"));
		serviceStationInfoMap.put("Email",MapUtils.getString(map,"email"));
		//serviceStationInfoMap.put("Fax",MapUtils.getString(map,""));
		//serviceStationInfoMap.put("Zipcode",MapUtils.getString(map,""));
		serviceStationInfoMap.put("BuildDate", MapUtils.getString(map, "authTime"));
		serviceStationInfoMap.put("CompanyType", "0");
		//serviceStationInfoMap.put("LegalPerson",MapUtils.getString(map,""));
		//serviceStationInfoMap.put("LegalMobile",MapUtils.getString(map,""));
		//serviceStationInfoMap.put("TaxCard",MapUtils.getString(map,""));
		//serviceStationInfoMap.put("TaxAddress",MapUtils.getString(map,""));
		//serviceStationInfoMap.put("BillType",MapUtils.getString(map,"","0"));
		//serviceStationInfoMap.put("BillName",MapUtils.getString(map,""));
		//serviceStationInfoMap.put("BillMobile",MapUtils.getString(map,""));
		//serviceStationInfoMap.put("BankName",MapUtils.getString(map,""));
		//serviceStationInfoMap.put("BankAccount",MapUtils.getString(map,""));
		//serviceStationInfoMap.put("BusinessScope",MapUtils.getString(map,""));
		//serviceStationInfoMap.put("BusinessAdd",MapUtils.getString(map,""));
		serviceStationInfoMap.put("PositionLat", MapUtils.getString(map, "positionLat"));
		serviceStationInfoMap.put("PositionLon", MapUtils.getString(map, "positionLon"));
		serviceStationInfoMap.put("Remark", MapUtils.getString(map, "remark"));
		//serviceStationInfoMap.put("FinalRejection",MapUtils.getString(map,""));
		//serviceStationInfoMap.put("Flag",MapUtils.getString(map,""));
		serviceStationInfoMap.put("Systime", LocalTimeUtil.getRealCurrentTime());
		serviceStationInfoMap.put("Conferend", MapUtils.getString(map, "conferend"));

		String serviceType = MapUtils.getString(map, "serviceType");
		if ("3".equals(serviceType)) {
			serviceType = "1,2";
		}
		serviceStationInfoMap.put("ServiceType", serviceType);
		serviceStationInfoMap.put("VehicleType", MapUtils.getString(map, "vehicleType"));
		serviceStationInfoMap.put("authorizedMode", MapUtils.getString(map, "authorizedMode"));

		serviceStationInfoMap.put("CompanyID", companyT.getId());
		serviceStationInfoMap.put("BusinessNo", MapUtils.getString(map, "stationNo"));
		String repairScope = MapUtils.getString(map, "repairScope");
		String ssAuth = "";
		if (StringUtils.isNotEmpty(repairScope)) {
			String[] scopes = repairScope.split(";");
			List<String> scopeList = Arrays.asList(scopes);
			if (CollectionUtils.isNotEmpty(scopeList)) {
				StringBuffer sb = new StringBuffer();
				for (String scope : scopeList) {
					String dicScope = dictionariesTService.getDictionaryDIntByDValue("SSAuth", scope);
					if (StringUtils.isNotEmpty(dicScope)) {
						sb.append(dicScope).append(";");
					} else {
						crmLogService.saveCrmErrorLog(companyT.getCompanyNo(), "syncStationInfo",
								JsonUtils.toJsonString(map), "排放等级映射失败，未获取到对应的排放信息");
					}
				}
				if (sb.length() > 0) {
					ssAuth = sb.substring(0, sb.length() - 1);
				}
			}
		}
		serviceStationInfoMap.put("SSAuth", ssAuth);
		serviceStationInfoMap.put("SSType", MapUtils.getString(map, "stationType"));
		serviceStationInfoMap.put("AuthTime", MapUtils.getString(map, "authTime"));
		String hotLine = MapUtils.getString(map, "hotLine");
		if (StringUtils.isNotEmpty(hotLine)) {
			if (hotLine.length() <= 20) {
				serviceStationInfoMap.put("HotlineTel", hotLine);
			} else {
				crmLogService.saveCrmErrorLog(companyT.getCompanyNo(), "syncStationInfo", JsonUtils.toJsonString(map),
						"服务商热线处理失败，超长数据无法处理");
			}
		}
		serviceStationInfoMap.put("Tel", MapUtils.getString(map, "telephone"));
		serviceStationInfoMap.put("ServiceStationCategory", MapUtils.getString(map, "dataType"));
		serviceStationInfoMap.put("SSFunStatus", 1);
		serviceStationInfoMap.put("DRFunStatus", 1);
		// 工单开闭开关
		/*Integer ssService = MapUtils.getInteger(map,"ssService");
		if(null != ssService){
			if(ssService.equals(1)){
				serviceStationInfoMap.put("SSFunStatus",1);
			}else{
				serviceStationInfoMap.put("SSFunStatus",0);
			}
		}
		Integer drService = MapUtils.getInteger(map,"drService");
		if(null != drService){
			if(drService.equals(1)){
				serviceStationInfoMap.put("DRFunStatus",1);
			}else{
				serviceStationInfoMap.put("DRFunStatus",0);
			}
		}*/
		serviceStationInfoMap.put("delearCatetory", MapUtils.getString(map, "delearCatetory"));
		//2.5.0  授权表增加授权级别字段
		serviceStationInfoMap.put("authorizationLevel", MapUtils.getString(map, "authorizationLevel"));
		serviceStationInfoMap.put("authorizationLevel", MapUtils.getString(map, "authorizationLevel"));
		//portal更新历史经销商数据 begin
		serviceStationInfoMap.put("region", MapUtils.getString(map, "region"));//所属大区
		serviceStationInfoMap.put("branchName", MapUtils.getString(map, "ccidb"));//分公司
		serviceStationInfoMap.put("authLevel", MapUtils.getString(map, "authLevel"));//授权等级
		serviceStationInfoMap.put("authArea", MapUtils.getString(map, "authArea"));//授权区域
		serviceStationInfoMap.put("authMarket", MapUtils.getString(map, "authMarket"));//授权市场
		serviceStationInfoMap.put("shareholderNameAndRatio", MapUtils.getString(map, "shareholderNameAndRatio"));//股东和持股
		serviceStationInfoMap.put("LegalPerson",MapUtils.getString(map,"legalPerson"));//法人信息
		//portal更新历史经销商数据 end
		return serviceStationInfoMap;
	}

	// 将接口数据转化成DCEC服务商数据-APPkey转换
	private Map<String, Object> getXCECServiceStationMap(Map<String, Object> map, Long serviceStationId,
														 CompanyT companyT) {
		Map<String, Object> serviceStationInfoMap = new HashMap<>();
		if (null != serviceStationId) {
			serviceStationInfoMap.put("ServiceStationID", serviceStationId);
		}
		// 服务商表ServiceStation_T
		serviceStationInfoMap.put("StationName", MapUtils.getString(map, "stationName"));
		serviceStationInfoMap.put("Abbreviation", MapUtils.getString(map, "shortName"));
		serviceStationInfoMap.put("Province", MapUtils.getString(map, "province"));
		serviceStationInfoMap.put("City", MapUtils.getString(map, "city"));
		serviceStationInfoMap.put("Area", MapUtils.getString(map, "area"));
		serviceStationInfoMap.put("Address", MapUtils.getString(map, "address"));
		serviceStationInfoMap.put("Contact", MapUtils.getString(map, "contact"));
		serviceStationInfoMap.put("Telephone", MapUtils.getString(map, "telephone"));
		serviceStationInfoMap.put("Phone", MapUtils.getString(map, "phone"));
		//serviceStationInfoMap.put("Email",MapUtils.getString(map,""));
		//serviceStationInfoMap.put("Fax",MapUtils.getString(map,""));
		//serviceStationInfoMap.put("Zipcode",MapUtils.getString(map,""));
		serviceStationInfoMap.put("BuildDate", MapUtils.getString(map, "authTime"));
		serviceStationInfoMap.put("CompanyType", "0");
		//serviceStationInfoMap.put("LegalPerson",MapUtils.getString(map,""));
		//serviceStationInfoMap.put("LegalMobile",MapUtils.getString(map,""));
		//serviceStationInfoMap.put("TaxCard",MapUtils.getString(map,""));
		//serviceStationInfoMap.put("TaxAddress",MapUtils.getString(map,""));
		//serviceStationInfoMap.put("BillType",MapUtils.getString(map,"","0"));
		//serviceStationInfoMap.put("BillName",MapUtils.getString(map,""));
		//serviceStationInfoMap.put("BillMobile",MapUtils.getString(map,""));
		//serviceStationInfoMap.put("BankName",MapUtils.getString(map,""));
		//serviceStationInfoMap.put("BankAccount",MapUtils.getString(map,""));
		//serviceStationInfoMap.put("BusinessScope",MapUtils.getString(map,""));
		//serviceStationInfoMap.put("BusinessAdd",MapUtils.getString(map,""));
		serviceStationInfoMap.put("PositionLat", MapUtils.getString(map, "positionLat"));
		serviceStationInfoMap.put("PositionLon", MapUtils.getString(map, "positionLon"));
		serviceStationInfoMap.put("Remark", MapUtils.getString(map, "remark"));
		//serviceStationInfoMap.put("FinalRejection",MapUtils.getString(map,""));
		//serviceStationInfoMap.put("Flag",MapUtils.getString(map,""));
		serviceStationInfoMap.put("Systime", LocalTimeUtil.getRealCurrentTime());
		serviceStationInfoMap.put("Conferend", MapUtils.getString(map, "conferend"));
		serviceStationInfoMap.put("EngineTypes", MapUtils.getString(map, "engineTypes"));//（SSHasEngineType） #####发动机机型，需要根据typeName反查EngineType表

		String serviceType = MapUtils.getString(map, "serviceType");
		if ("3".equals(serviceType)) {
			serviceType = "1,2";
		}
		serviceStationInfoMap.put("ServiceType", serviceType);
		serviceStationInfoMap.put("VehicleType", MapUtils.getString(map, "vehicleType"));

		serviceStationInfoMap.put("CompanyID", companyT.getId());
		serviceStationInfoMap.put("BusinessNo", MapUtils.getString(map, "stationNo"));
		String repairScope = MapUtils.getString(map, "repairScope");
		/*String ssAuth = "";
		if (StringUtils.isNotEmpty(repairScope)) {
		    String[] scopes = repairScope.split(";");
		    List<String> scopeList = Arrays.asList(scopes);
		    if (CollectionUtils.isNotEmpty(scopeList)) {
		        StringBuffer sb = new StringBuffer();
		        for (String scope : scopeList) {
		            String dicScope = dictionariesTService.getDictionaryDIntByDValue("SSAuth", scope);
		            if (StringUtils.isNotEmpty(dicScope)) {
		                sb.append(dicScope).append(";");
		            } else {
		                crmLogService.saveCrmErrorLog(companyT.getCompanyNo(), "syncStationInfo", JsonUtils.toJsonString(map), "排放等级映射失败，未获取到对应的排放信息");
		            }
		        }
		        if (sb.length() > 0) {
		            ssAuth = sb.substring(0, sb.length() - 1);
		        }
		    }
		}*/
		serviceStationInfoMap.put("SSAuth", repairScope.replace(";", ","));
		serviceStationInfoMap.put("SSType", MapUtils.getString(map, "stationType"));
		serviceStationInfoMap.put("AuthTime", MapUtils.getString(map, "authTime"));
		String hotLine = MapUtils.getString(map, "hotLine");
		if (StringUtils.isNotEmpty(hotLine)) {
			if (hotLine.length() <= 20) {
				serviceStationInfoMap.put("HotlineTel", hotLine);
			} else {
				crmLogService.saveCrmErrorLog(companyT.getCompanyNo(), "syncStationInfo", JsonUtils.toJsonString(map),
						"服务商热线处理失败，超长数据无法处理");
			}
		}
		serviceStationInfoMap.put("Tel", MapUtils.getString(map, "telephone"));
		Integer ssService = MapUtils.getInteger(map, "ssService");
		if (null != ssService) {
			if (ssService.equals(1)) {
				serviceStationInfoMap.put("SSFunStatus", 1);
			} else {
				serviceStationInfoMap.put("SSFunStatus", 0);
			}
		}
		Integer drService = MapUtils.getInteger(map, "drService");
		if (null != drService) {
			if (drService.equals(1)) {
				serviceStationInfoMap.put("DRFunStatus", 1);
			} else {
				serviceStationInfoMap.put("DRFunStatus", 0);
			}
		}
		serviceStationInfoMap.put("isTechSupport", MapUtils.getBoolean(map, "isBigCraftsman", false) ? 1 : 0);
		return serviceStationInfoMap;
	}

	// 将接口数据转化成XCEC服务商数据-APPkey转换
	private Map<String, Object> getDCECServiceStationMap(Map<String, Object> map, Long serviceStationId,
														 CompanyT companyT) {
		Map<String, Object> serviceStationInfoMap = new HashMap<>();
		if (null != serviceStationId) {
			serviceStationInfoMap.put("ServiceStationID", serviceStationId);
		}
		// 服务商表ServiceStation_T
		serviceStationInfoMap.put("StationName", MapUtils.getString(map, "stationName"));
		serviceStationInfoMap.put("Abbreviation", MapUtils.getString(map, "shortName"));
		serviceStationInfoMap.put("Province", MapUtils.getString(map, "province"));
		serviceStationInfoMap.put("City", MapUtils.getString(map, "city"));
		serviceStationInfoMap.put("Area", MapUtils.getString(map, "area"));
		serviceStationInfoMap.put("Address", MapUtils.getString(map, "address"));
		serviceStationInfoMap.put("Contact", MapUtils.getString(map, "contact"));
		serviceStationInfoMap.put("Telephone", MapUtils.getString(map, "telephone"));
		serviceStationInfoMap.put("Phone", MapUtils.getString(map, "phone"));
		serviceStationInfoMap.put("BuildDate", MapUtils.getString(map, "authTime"));
		serviceStationInfoMap.put("CompanyType", "0");
		serviceStationInfoMap.put("PositionLat", MapUtils.getString(map, "positionLat"));
		serviceStationInfoMap.put("PositionLon", MapUtils.getString(map, "positionLon"));
		serviceStationInfoMap.put("Remark", MapUtils.getString(map, "remark"));
		serviceStationInfoMap.put("Systime", LocalTimeUtil.getRealCurrentTime());
		serviceStationInfoMap.put("Conferend", MapUtils.getString(map, "conferend"));
		serviceStationInfoMap.put("EngineTypes", MapUtils.getString(map, "engineTypes"));//（SSHasEngineType） #####发动机机型，需要根据typeName反查EngineType表
		// DCEC需求	20210510
		serviceStationInfoMap.put("RequestStatus", MapUtils.getString(map, "requstStatus"));

		String serviceType = MapUtils.getString(map, "serviceType");
		if ("3".equals(serviceType)) {
			serviceType = "1,2";
		}
		serviceStationInfoMap.put("ServiceType", serviceType);
		serviceStationInfoMap.put("VehicleType", MapUtils.getString(map, "vehicleType"));

		serviceStationInfoMap.put("CompanyID", companyT.getId());
		serviceStationInfoMap.put("BusinessNo", MapUtils.getString(map, "stationNo"));
		String repairScope = MapUtils.getString(map, "repairScope");

		serviceStationInfoMap.put("SSAuth", repairScope.replace(";", ","));
		serviceStationInfoMap.put("SSType", MapUtils.getString(map, "stationType"));
		serviceStationInfoMap.put("AuthTime", MapUtils.getString(map, "authTime"));
		String hotLine = MapUtils.getString(map, "hotLine");
		if (StringUtils.isNotEmpty(hotLine)) {
			if (hotLine.length() <= 20) {
				serviceStationInfoMap.put("HotlineTel", hotLine);
			} else {
				crmLogService.saveCrmErrorLog(companyT.getCompanyNo(), "syncStationInfo", JsonUtils.toJsonString(map),
						"服务商热线处理失败，超长数据无法处理");
			}
		}
		serviceStationInfoMap.put("Tel", MapUtils.getString(map, "telephone"));
		Integer ssService = MapUtils.getInteger(map, "ssService");
		if (null != ssService) {
			if (ssService.equals(1)) {
				serviceStationInfoMap.put("SSFunStatus", 1);
			} else {
				serviceStationInfoMap.put("SSFunStatus", 0);
			}
		}
		Integer drService = MapUtils.getInteger(map, "drService");
		if (null != drService) {
			if (drService.equals(1)) {
				serviceStationInfoMap.put("DRFunStatus", 1);
			} else {
				serviceStationInfoMap.put("DRFunStatus", 0);
			}
		}

		String fatherStationNo = MapUtils.getString(map, "fatherStationNo");
		// 空为一网，非空为二网,RelationType为空/null/1表示一网，2表示二网
		if (!StringUtils.isEmpty(fatherStationNo)) {
			serviceStationInfoMap.put("RelationType", 2);
		}
		return serviceStationInfoMap;
	}

	private Map<String, Object> geCCECServiceStationMap(Map<String, Object> map, Long serviceStationId,
														CompanyT companyT) {
		Map<String, Object> serviceStationInfoMap = new HashMap<>();
		if (null != serviceStationId) {
			serviceStationInfoMap.put("ServiceStationID", serviceStationId);
		}
		// 服务商表ServiceStation_T
		serviceStationInfoMap.put("StationName", MapUtils.getString(map, "stationName"));
		serviceStationInfoMap.put("Abbreviation", MapUtils.getString(map, "shortName"));
		serviceStationInfoMap.put("Province", MapUtils.getString(map, "province"));
		serviceStationInfoMap.put("City", MapUtils.getString(map, "city"));
		serviceStationInfoMap.put("Area", MapUtils.getString(map, "area"));
		serviceStationInfoMap.put("Address", MapUtils.getString(map, "address"));
		serviceStationInfoMap.put("Contact", MapUtils.getString(map, "contact"));
		serviceStationInfoMap.put("Telephone", MapUtils.getString(map, "telephone"));
		serviceStationInfoMap.put("Phone", MapUtils.getString(map, "phone"));
		//serviceStationInfoMap.put("Email",MapUtils.getString(map,""));
		//serviceStationInfoMap.put("Fax",MapUtils.getString(map,""));
		//serviceStationInfoMap.put("Zipcode",MapUtils.getString(map,""));
		serviceStationInfoMap.put("BuildDate", MapUtils.getString(map, "authTime"));
		serviceStationInfoMap.put("CompanyType", "0");
		//serviceStationInfoMap.put("LegalPerson",MapUtils.getString(map,""));
		//serviceStationInfoMap.put("LegalMobile",MapUtils.getString(map,""));
		//serviceStationInfoMap.put("TaxCard",MapUtils.getString(map,""));
		//serviceStationInfoMap.put("TaxAddress",MapUtils.getString(map,""));
		//serviceStationInfoMap.put("BillType",MapUtils.getString(map,"","0"));
		//serviceStationInfoMap.put("BillName",MapUtils.getString(map,""));
		//serviceStationInfoMap.put("BillMobile",MapUtils.getString(map,""));
		//serviceStationInfoMap.put("BankName",MapUtils.getString(map,""));
		//serviceStationInfoMap.put("BankAccount",MapUtils.getString(map,""));
		//serviceStationInfoMap.put("BusinessScope",MapUtils.getString(map,""));
		//serviceStationInfoMap.put("BusinessAdd",MapUtils.getString(map,""));
		serviceStationInfoMap.put("PositionLat", MapUtils.getString(map, "positionLat"));
		serviceStationInfoMap.put("PositionLon", MapUtils.getString(map, "positionLon"));
		serviceStationInfoMap.put("Remark", MapUtils.getString(map, "remark"));
		//serviceStationInfoMap.put("FinalRejection",MapUtils.getString(map,""));
		//serviceStationInfoMap.put("Flag",MapUtils.getString(map,""));
		serviceStationInfoMap.put("Systime", LocalTimeUtil.getRealCurrentTime());
		serviceStationInfoMap.put("Conferend", MapUtils.getString(map, "conferend"));

		String serviceType = MapUtils.getString(map, "serviceType");
		if ("3".equals(serviceType)) {
			serviceType = "1,2";
		}
		serviceStationInfoMap.put("ServiceType", serviceType);
		serviceStationInfoMap.put("VehicleType", MapUtils.getString(map, "vehicleType"));
		serviceStationInfoMap.put("authorizedMode", MapUtils.getString(map, "authorizedMode"));

		serviceStationInfoMap.put("CompanyID", companyT.getId());
		serviceStationInfoMap.put("BusinessNo", MapUtils.getString(map, "stationNo"));
		String repairScope = MapUtils.getString(map, "repairScope");
		String ssAuth = "";
		if (StringUtils.isNotEmpty(repairScope)) {
			String[] scopes = repairScope.split(";");
			List<String> scopeList = Arrays.asList(scopes);
			if (CollectionUtils.isNotEmpty(scopeList)) {
				StringBuffer sb = new StringBuffer();
				for (String scope : scopeList) {
					String dicScope = dictionariesTService.getDictionaryDIntByDValue("SSAuth", scope);
					if (StringUtils.isNotEmpty(dicScope)) {
						sb.append(dicScope).append(";");
					} else {
						crmLogService.saveCrmErrorLog(companyT.getCompanyNo(), "syncStationInfo",
								JsonUtils.toJsonString(map), "排放等级映射失败，未获取到对应的排放信息");
					}
				}
				if (sb.length() > 0) {
					ssAuth = sb.substring(0, sb.length() - 1);
				}
			}
		}
		serviceStationInfoMap.put("SSAuth", ssAuth);
		serviceStationInfoMap.put("SSType", MapUtils.getString(map, "stationType"));
		serviceStationInfoMap.put("AuthTime", MapUtils.getString(map, "authTime"));
		String hotLine = MapUtils.getString(map, "hotLine");
		if (StringUtils.isNotEmpty(hotLine)) {
			if (hotLine.length() <= 20) {
				serviceStationInfoMap.put("HotlineTel", hotLine);
			} else {
				crmLogService.saveCrmErrorLog(companyT.getCompanyNo(), "syncStationInfo", JsonUtils.toJsonString(map),
						"服务商热线处理失败，超长数据无法处理");
			}
		}
		serviceStationInfoMap.put("Tel", MapUtils.getString(map, "telephone"));
		serviceStationInfoMap.put("ServiceStationCategory", MapUtils.getString(map, "dataType"));

		serviceStationInfoMap.put("serviceScope", MapUtils.getString(map, "serviceScope"));
		serviceStationInfoMap.put("superiorDepartment", MapUtils.getString(map, "superiorDepartment"));

		// 工单开闭开关
		Integer ssService = MapUtils.getInteger(map, "ssService");
		if (null != ssService) {
			if (ssService.equals(1)) {
				serviceStationInfoMap.put("SSFunStatus", 1);
			} else {
				serviceStationInfoMap.put("SSFunStatus", 0);
			}
		}
		Integer drService = MapUtils.getInteger(map, "drService");
		if (null != drService) {
			if (drService.equals(1)) {
				serviceStationInfoMap.put("DRFunStatus", 1);
			} else {
				serviceStationInfoMap.put("DRFunStatus", 0);
			}
		}

		return serviceStationInfoMap;
	}

	/**
	 * 根据工单编号获取外出轨迹点
	 */
	@Override
	public ModelAndView getWorkOrderTracks(Map<String, Object> httpMap) {
		String serviceChannel = MapUtils.getString(httpMap, "company", "");
		if (!serviceChannel.equals("CCEC") && !serviceChannel.equals("DCEC")) {
			return getTrackPage(httpMap);
		} else {
			HttpServletResponse response = (HttpServletResponse) httpMap.get("response");
			String orderNo = MapUtils.getString(httpMap, "orderNo", "");
			String viewUrl = PropertiesUtil.getProperties("projectconfig.properties", "trackPagesUrl");
			String url = String.format("%s%s", viewUrl, AESTool.encryptString(orderNo));
			Map<String, Object> dataMap = new HashMap<>();
			dataMap.put("url", url);
			ParameterTool.writeSuccessResponse(response, dataMap);
			return null;
		}
	}


	/**
	 * 2.10.0 增加了返回的轨迹参数
	 */
	private TrackParameters getTrackParameters(String orderNo) {
		TrackParameters trackParameters = new TrackParameters();
		trackParameters.setOrderNo(orderNo);

		WorkOrderT wo = workOrderTDao.selectWorkOrderByOrderNo(orderNo);
		if (!Objects.isNull(wo)) {
			trackParameters.setServiceCarNo(wo.getServiceCarNo() == null ? "" : wo.getServiceCarNo());
			// 如果服务工单为外出工单，那么查询出外出时间跟到达时间
			if (wo.getIsOutside() == 1) {
				// 获取技师的外出以及到达时间
				List<WorkOrderFlow> workOrderFlows = workOrderFlowTDao.getTechnicianOutAndArrivedTimeByOrderId(wo.getId());

				if (CollectionUtils.isNotEmpty(workOrderFlows)) {
					for (WorkOrderFlow wof : workOrderFlows) {
						Integer orderStatus = wof.getProcessStatus();

						LOG.info(String.format("OrderStatus:%s CreateTime:%s IMEI:%s", orderStatus, wof.getCreateTime(), wof.getImei()));
						switch (orderStatus) {
							// 10:出发状态
							case 10:
								trackParameters.setOutTime(wof.getCreateTime());
								trackParameters.setOutIMEI(wof.getImei());
								break;
							// 11:到达状态
							case 11:
								trackParameters.setArrivedTime(wof.getCreateTime());
								trackParameters.setArrivedIMEI(wof.getImei());
								break;
						}
					}
				}
			}

			// 查询出主副技师
			List<TrackTechnician> trackTechnicians = workOrderPrincipalTDao.getTechnicianByOrderId(wo.getId());
			if (CollectionUtils.isNotEmpty(trackTechnicians)) {
				// 将trackTechnicians按isPrincipal分组(1：主技师 0：副技师)
				Map<Integer, List<String>> techGroup = trackTechnicians.stream()
						.collect(
								Collectors.groupingBy(
										TrackTechnician::getIsPrincipal,
										Collectors.mapping(
												TrackTechnician::getName,
												Collectors.toList()
										)
								)
						);


				// 设置主技师的姓名
				trackParameters.setMainTechnician(techGroup.get(1) == null ? new ArrayList<>() : techGroup.get(1));
				// 设置副技师的姓名
				trackParameters.setSecondaryTechnician(techGroup.get(0) == null ? new ArrayList<>() : techGroup.get(0));
				LOG.info("主副技师：" + techGroup);
			}
		}
		return trackParameters;
	}

    //手动重传srt异常数据到crm
	@Override
	public void retryExceptionDataSyncCrm(Map<String, Object> map){
		LOG.info("进入手动重传srt异常数据到crm接口");
		String ids = MapUtils.getString(map,"ids","");
		List<Map<String,Object>> exceptionDataSyncCrmTSyncFailureList = new ArrayList<>();
		if(StringUtils.isNotEmpty(ids)){
            List<String> stringList = StringToool.getStringList(ids, ",");
            exceptionDataSyncCrmTSyncFailureList = exceptionDataSyncCrmTDao.getExceptionDataSyncCrmTSyncFailureListByIds(stringList);
        }else{
			exceptionDataSyncCrmTSyncFailureList = exceptionDataSyncCrmTDao.getExceptionDataSyncCrmTSyncFailureList();
		}
		try {
			if(CollectionUtils.isNotEmpty(exceptionDataSyncCrmTSyncFailureList)){
				exceptionDataSyncCrmTSyncFailureList.stream().forEach(exceptionDataSyncCrmTSyncFailure->{
					String mapStr = MapUtils.getString(exceptionDataSyncCrmTSyncFailure,"ExceptionData","");
					if(StringUtils.isNotEmpty(mapStr)){
						Map<String,Object> contentJsonMap = JSON.parseObject(mapStr);
						CRMResponeEntity CRMres = CRMApiUtils.getCRMServiceApi().syncRepairAckToCRM("CCI",platformServiceDao,redisClientUtils,contentJsonMap);
						Map<String,Object> updateExceptionDataSyncCrmTMap = new HashMap<>();
						updateExceptionDataSyncCrmTMap.put("Updator",-1);
						updateExceptionDataSyncCrmTMap.put("UpdateTime",LocalTimeUtil.getRealCurrentTime());
						updateExceptionDataSyncCrmTMap.put("ID",MapUtils.getLongValue(exceptionDataSyncCrmTSyncFailure,"ID"));
						if(CRMres.getStatus()!=0) {
							String errorMsg = "手动同步确认维修信息至CRM失败，状态："+CRMres.getStatus()+"，用户信息:"+CRMres.getMessage();
							updateExceptionDataSyncCrmTMap.put("FailReason",errorMsg);
							//APP同步工单信息到CRM系统失败
							LOG.info(errorMsg);
						}else{
							updateExceptionDataSyncCrmTMap.put("IsSyncSuccess",1);
						}
						exceptionDataSyncCrmTDao.update(updateExceptionDataSyncCrmTMap);
					}
				});
			}
		} catch (Exception e) {
			LOG.info("手动同步srt确认维修数据到crm发生异常，异常信息" + e.getMessage(), e);
		}
		LOG.info("手动重传srt异常数据到crm接口结束");
	}


	/**
	 * 轨迹参数
	 */
	class TrackParameters {
		// 订单号
		private String orderNo = "";
		// 车牌号
		private String serviceCarNo = "";
		// 出发时间
		private String outTime = "";
		// 到达时间
		private String arrivedTime = "";
		// 主技师
		private List<String> mainTechnician;
		// 副技师
		private List<String> secondaryTechnician;
		// 出发手机串号
		private String outIMEI = "";
		// 到达手机串号
		private String arrivedIMEI = "";


		public String getOrderNo() {
			return orderNo;
		}

		public void setOrderNo(String orderNo) {
			this.orderNo = orderNo;
		}

		public String getServiceCarNo() {
			return serviceCarNo;
		}

		public void setServiceCarNo(String serviceCarNo) {
			this.serviceCarNo = serviceCarNo;
		}

		public String getOutTime() {
			return outTime;
		}

		public void setOutTime(String outTime) {
			this.outTime = outTime;
		}

		public String getArrivedTime() {
			return arrivedTime;
		}

		public void setArrivedTime(String arrivedTime) {
			this.arrivedTime = arrivedTime;
		}

		public List<String> getMainTechnician() {
			return mainTechnician;
		}

		public void setMainTechnician(List<String> mainTechnician) {
			this.mainTechnician = mainTechnician;
		}

		public List<String> getSecondaryTechnician() {
			return secondaryTechnician;
		}

		public void setSecondaryTechnician(List<String> secondaryTechnician) {
			this.secondaryTechnician = secondaryTechnician;
		}

		public String getOutIMEI() {
			return outIMEI;
		}

		public void setOutIMEI(String outIMEI) {
			this.outIMEI = outIMEI;
		}

		public String getArrivedIMEI() {
			return arrivedIMEI;
		}

		public void setArrivedIMEI(String arrivedIMEI) {
			this.arrivedIMEI = arrivedIMEI;
		}

	}


	@Override
	public ModelAndView getTrackPages(Map<String, Object> httpMap) {
		String orderNo = MapUtils.getString(httpMap, "orderNo", "");
		httpMap.put("orderNo", AESTool.decryptString(orderNo));
		//httpMap.put("orderNo", orderNo);
		return getTrackPage(httpMap);
	}


	private ModelAndView getTrackPage(Map<String, Object> map) {
		HttpServletRequest request = (HttpServletRequest) map.get("request");
		String orderNo = MapUtils.getString(map, "orderNo", "");
		if (StringUtils.isBlank(orderNo)) {
			// 缺少必要参数
			request.setAttribute("result", 1);
			ModelAndView mav = new ModelAndView("test");
			return mav;
		}


		// 2.10.0 页面增加服务车车牌号、出发时间、到达时间等字段
		TrackParameters trackParameters = getTrackParameters(orderNo);
		request.setAttribute("serviceCarNo", trackParameters.getServiceCarNo());
		request.setAttribute("outTime", trackParameters.getOutTime());
		request.setAttribute("arrivedTime", trackParameters.getArrivedTime());
		request.setAttribute("mainTechnician", trackParameters.getMainTechnician());
		request.setAttribute("secondaryTechnician", trackParameters.getSecondaryTechnician());
		request.setAttribute("outIMEI", trackParameters.getOutIMEI());
		request.setAttribute("arrivedIMEI", trackParameters.getArrivedIMEI());


		//根据工单编号获取工单信息
		Map<String, Object> orderMap = workOrderTDao.getOrderByNo(orderNo);
		if (MapUtils.isNotEmpty(orderMap)) {
			request.setAttribute("orderChannel", MapUtils.getLongValue(orderMap, "OrderChannel"));
		}

		long orderId = MapUtils.getLongValue(orderMap, "ID");
		//获取出发到达经纬   页面中起始点和终点位置用下面的逻辑
		Map<String, Object> startJWD = workOrderFlowTDao.getWorkOrderFlowByOrderIdAndStatus(orderId, 10);
		Map<String, Object> endJWD = workOrderFlowTDao.getWorkOrderFlowByOrderIdAndStatus(orderId, 11);
		Double startLocLon = MapUtils.getDouble(startJWD, "LocLon", 0.0);
		Double startLocLat = MapUtils.getDouble(startJWD, "LocLat", 0.0);
		Double endLocLon = MapUtils.getDouble(endJWD, "LocLon", 0.0);
		Double endLocLat = MapUtils.getDouble(endJWD, "LocLat", 0.0);

		//sprint34需求 维修点 可能中途发生变更 计算取最新维修点进行计算

		//原地址坐标
		Double repairLocLon = 0.0;
		Double repairLocLat = 0.0;

//		//如果变更点存在则按照变更点计算
//		if (!Objects.isNull(orderMap.get("ReplaceLon")) && !Objects.isNull(orderMap.get("ReplaceLat"))){
//			repairLocLon = MapUtils.getDouble(orderMap, "ReplaceLon", 0.0);
//			repairLocLat = MapUtils.getDouble(orderMap, "ReplaceLat", 0.0);
//		}else{
		// 故障点
			 repairLocLon = MapUtils.getDouble(orderMap, "LocLon", 0.0);
			 repairLocLat = MapUtils.getDouble(orderMap, "LocLat", 0.0);
//		}

		Double[] startEndArr = new Double[10];
		startEndArr[0] = startLocLon;
		startEndArr[1] = startLocLat;

		startEndArr[2] = endLocLon;
		startEndArr[3] = endLocLat;

		startEndArr[4] = repairLocLon;
		startEndArr[5] = repairLocLat;

		long channel = MapUtils.getLongValue(orderMap, "OrderChannel");
		//sprint34添加需求 重康添加变更点坐标
		if (Long.valueOf(109).equals(channel) && !Objects.isNull(orderMap.get("ReplaceLon")) && !Objects.isNull(orderMap.get("ReplaceLat"))){
			//变更后的新维修点的坐标
			startEndArr[6] = MapUtils.getDouble(orderMap, "ReplaceLon", 0.0);
			startEndArr[7] = MapUtils.getDouble(orderMap, "ReplaceLat", 0.0);
			//变更时的当前坐标
			startEndArr[8] = MapUtils.getDouble(orderMap, "CurrentLon", 0.0);
			startEndArr[9] = MapUtils.getDouble(orderMap, "CurrentLat", 0.0);

			request.setAttribute("ChangePositionTime",orderMap.get("ChangePositionTime"));
		}

		JSONArray startEndArr2 = new JSONArray();
		startEndArr2 = JSONArray.fromObject(startEndArr);
		// 放入request域
		request.setAttribute("startEndArr", startEndArr2);

		// 根据工单编号查询工单轨迹
		List<Map<String, Object>> list = new ArrayList<>();
		list = crmServiceDao.getWorkOrderTrack(orderNo);

		//2.9.0需求增加出发和到达点的地址
		request.setAttribute("startLocation", workOrderFlowTDao.getLocationByOrderIdProcessStatus(orderId, 10));
		request.setAttribute("endLocation", workOrderFlowTDao.getLocationByOrderIdProcessStatus(orderId, 11));

		if (null != list && list.size() > 0) {

			Double[] startArr = new Double[2];
			startArr[0] = MapUtils.getDouble(list.get(0), "LocLon", 0.0);
			startArr[1] = MapUtils.getDouble(list.get(0), "LocLat", 0.0);
			JSONArray sja = new JSONArray();
			sja = JSONArray.fromObject(startArr);

			// 放入request域
			request.setAttribute("orderStatus",orderMap.get("OrderStatus").toString());
			request.setAttribute("gpsStartData", sja);
			// 外出里程信息
			request.setAttribute("GuessDistance", MapUtils.getString(list.get(0), "GuessDistance", ""));
			request.setAttribute("RealDistance", MapUtils.getString(list.get(0), "RealDistance", ""));
			request.setAttribute("AdjustDistance", MapUtils.getString(list.get(0), "AdjustDistance", ""));
			String orderChannel = MapUtils.getString(orderMap, "OrderChannel");
			if ("109".equals(orderChannel)) {
				//3.1.0运维版本时间最快计划里程更新为出发点到故障点的时间最快里程
				//距离最短计划里程更新为故障点到终点的时间最快里程
				//技师填写里程更新为  +=出发点到报修点+报修点到到达点=总值   -=出发点到报修点-报修点到到达点=值
				//下面那两个字段不确定别的地方是否用到       暂不注释
				String fastestDistance = MapUtils.getString(orderMap, "FastestDistance", "0.0");
				request.setAttribute("FastestDistance", fastestDistance);
				String shortestDistance = MapUtils.getString(orderMap, "ShortestDistance", "0.0");
				request.setAttribute("ShortestDistance", shortestDistance);
				//sprint34新增需求 要求路径按照高德中的0，2，4策略计算(速度优先,距离优先,躲避拥堵)里程 取最大值相加 获得最后结果

				//如果变更点存在则按照变更点计算
				//计算用的地址坐标
				Double repairLocLonReckon = 0.0;
				Double repairLocLatReckon = 0.0;
				if (!Objects.isNull(orderMap.get("ReplaceLon")) && !Objects.isNull(orderMap.get("ReplaceLat"))){
					repairLocLonReckon = MapUtils.getDouble(orderMap, "ReplaceLon", 0.0);
					repairLocLatReckon = MapUtils.getDouble(orderMap, "ReplaceLat", 0.0);
				}else{
					//故障点
					repairLocLonReckon = MapUtils.getDouble(orderMap, "LocLon", 0.0);
					repairLocLatReckon = MapUtils.getDouble(orderMap, "LocLat", 0.0);
				}
				//获取出发点故障点的里程
				BigDecimal startToRepariFastestDriveDistanceBig = getComparisonDistance(startLocLon.toString(), startLocLat.toString(), repairLocLonReckon.toString(), repairLocLatReckon.toString());

				//故障点到到达点最快里程
				BigDecimal repariToEndFastestDriveDistanceBig = getComparisonDistance(repairLocLonReckon.toString(), repairLocLatReckon.toString(), endLocLon.toString(), endLocLat.toString());

				request.setAttribute("startToRepariFastestDistance", startToRepariFastestDriveDistanceBig);
				request.setAttribute("repariToEndFastestDistance", repariToEndFastestDriveDistanceBig);
				DecimalFormat df = new DecimalFormat("######0.00");
				//工单状态是已到达:11 显示出发点-报修点-到达点 的值，如果未到达不显示
				if(endLocLon != 0.0 && endLocLat != 0.0){
					request.setAttribute("oneAddTwoDistance", df.format(startToRepariFastestDriveDistanceBig.doubleValue() + repariToEndFastestDriveDistanceBig.doubleValue()));
				} else {
					request.setAttribute("oneAddTwoDistance", "");
				}
				request.setAttribute("oneMinusTwoDistance", df.format(startToRepariFastestDriveDistanceBig.doubleValue() - repariToEndFastestDriveDistanceBig.doubleValue()));
				LOG.info("获取工单行驶轨迹getTrackPage接口，ccec获取出发点到故障点最快里程为" + startToRepariFastestDriveDistanceBig + "，ccec获取故障点到到达点最快里程为" + repariToEndFastestDriveDistanceBig);
			}

			//2.5.0需求    ccec计划里程逻辑变更为主技师出发点到故障点之间的距离
			String planDistance = MapUtils.getString(list.get(0), "PlanDistance", "");
			request.setAttribute("PlanDistance", planDistance);

			JSONArray ja = new JSONArray();
			// arrived用来保存(到达-服务完成)的坐标点
			JSONArray arrived = new JSONArray();

			boolean flag = false;
			for (Map<String, Object> map2 : list) {
				Object orderStatus = map2.get("WOStatus");
				if (orderStatus != null) {
					flag = true;
					break;
				}
			}

			// 如果WOStatus为空时，集合ja保存所有的坐标点(出发-达到-服务完成)否则只包含(出发-到达)的坐标点
			// WorkOrderTrack_T里增加了OrderStatus字段，为了兼容之前的版本WOStatus为空时地图的路线不区分颜色，否则地图路线区分颜色。
			if (!flag) {
				for (int i = 0; i < list.size(); i++) {
					JSONObject gpsJb = new JSONObject();
					Double locLon = MapUtils.getDouble(list.get(i), "LocLon", 0.0);
					Double locLat = MapUtils.getDouble(list.get(i), "LocLat", 0.0);
					gpsJb.put("x", locLon);
					gpsJb.put("y", locLat);
					gpsJb.put("sp", 0);
					gpsJb.put("ag", 0);
					gpsJb.put("tm", i + 1);
					ja.add(gpsJb);
				}
			} else {
				int a = 0, b = 0;
				// 循环集合并根据状态划分出2个集合  1.保存出发-到达的坐标点   2.保存到达-服务完成的坐标点
				for (int i = 0; i < list.size(); i++) {
					Map<String, Object> m = list.get(i);
					JSONObject gpsJb = new JSONObject();
					Double locLon = MapUtils.getDouble(m, "LocLon", 0.0);
					Double locLat = MapUtils.getDouble(m, "LocLat", 0.0);
					gpsJb.put("x", locLon);
					gpsJb.put("y", locLat);
					gpsJb.put("sp", 0);
					gpsJb.put("ag", 0);

					if (m.get("WOStatus") == null || m.get("WOStatus").equals(10)) {
						gpsJb.put("tm", ++a);
						ja.add(gpsJb);
					} else {
						gpsJb.put("tm", ++b);
						arrived.add(gpsJb);
					}
				}

				// 保存到达点的坐标
				if (CollectionUtils.isNotEmpty(ja)) {
					JSONObject gpsJb = new JSONObject();
					gpsJb.put("x", startEndArr[2]);
					gpsJb.put("y", startEndArr[3]);
					gpsJb.put("sp", 0);
					gpsJb.put("ag", 0);
					gpsJb.put("tm", ++a);
					ja.add(gpsJb);
				}

				if (CollectionUtils.isNotEmpty(arrived)) {
					JSONArray _temp = new JSONArray();
					JSONObject gpsJb = new JSONObject();
					gpsJb.put("x", startEndArr[2]);
					gpsJb.put("y", startEndArr[3]);
					gpsJb.put("sp", 0);
					gpsJb.put("ag", 0);
					gpsJb.put("tm", 0);

					_temp.add(gpsJb);
					_temp.addAll(arrived);
					arrived = _temp;
				}

			}

			// 将位置点返回页面
			request.setAttribute("gpsData", ja);
			// TODO ===修改达到-服务完成轨迹颜色
			// 保存(达到-服务完成)坐标点
			request.setAttribute("arrived", arrived);

			JSONArray nja = new JSONArray();
			if (CollectionUtils.isNotEmpty(list)) {
				for (int i = 0; i < list.size(); i++) {
					JSONObject gpsJb = new JSONObject();
					Double locLon = MapUtils.getDouble(list.get(i), "x", 0.0);
					Double locLat = MapUtils.getDouble(list.get(i), "y", 0.0);
					gpsJb.put("x", locLon);
					gpsJb.put("y", locLat);
					gpsJb.put("sp", 0);
					gpsJb.put("ag", 0);
					gpsJb.put("tm", i + 1);
					nja.add(gpsJb);
				}
			}

			request.setAttribute("ngpsData", nja);
			// 成功
			request.setAttribute("result", 0);
		} else {
			// 未查询到该工单的轨迹信息
			request.setAttribute("result", 2);
		}
		ModelAndView mav = new ModelAndView("test");
		return mav;
	}
	//sprint34新增需求 要求路径按照高德中的0，2，4策略计算(速度优先,距离优先,躲避拥堵)里程 取最大值相加 获得最后结果
	private BigDecimal getComparisonDistance(String startLocLon, String startLocLat, String repairLocLon, String repairLocLat) {
		//获取不同策略中两点之间的里程,比较选取最大里程返回
		Map<String, Object> fastestMap = GDRegion.direction(GDRegion.DirectionType.FASTEST, startLocLon.toString(), startLocLat.toString(), repairLocLon.toString(), repairLocLat.toString());
		Long fastestDistance = MapUtils.getLong(fastestMap, "distance", 0l);
		BigDecimal fastestDriveDistance = new BigDecimal(fastestDistance);
		BigDecimal fastestDriveDistanceBig = fastestDriveDistance.divide(BigDecimal.valueOf(1000L), 2, RoundingMode.DOWN);

		Map<String, Object> shortestMap = GDRegion.direction(GDRegion.DirectionType.SHORTEST, startLocLon.toString(), startLocLat.toString(), repairLocLon.toString(), repairLocLat.toString());
		Long shortestDistance = MapUtils.getLong(shortestMap, "distance", 0l);
		BigDecimal sshortestDriveDistance = new BigDecimal(shortestDistance);
		BigDecimal shortestDriveDistanceBig = sshortestDriveDistance.divide(BigDecimal.valueOf(1000L), 2, RoundingMode.DOWN);

		BigDecimal middle = fastestDriveDistanceBig.max(shortestDriveDistanceBig);

		Map<String, Object> avoidCongestionMap = GDRegion.direction(GDRegion.DirectionType.AVOID_CONGESTION, startLocLon.toString(), startLocLat.toString(), repairLocLon.toString(), repairLocLat.toString());
		Long avoidCongestionDistance = MapUtils.getLong(avoidCongestionMap, "distance", 0l);
		BigDecimal avoidCongestionDriveDistance = new BigDecimal(avoidCongestionDistance);
		BigDecimal avoidCongestionDriveDistanceBig = avoidCongestionDriveDistance.divide(BigDecimal.valueOf(1000L), 2, RoundingMode.DOWN);

		BigDecimal max = middle.max(avoidCongestionDriveDistanceBig);
		return max;
	}

	@Transactional
	@Override
	public ModelAndView syncEngineerQualifyInfos(Map<String, Object> httpMap) {

		HttpServletRequest request = (HttpServletRequest) httpMap.get("request");
		HttpServletResponse response = (HttpServletResponse) httpMap.get("response");
		String companyStr = httpMap.get("company").toString();
		// 新增DCEC逻辑：由原来的机型匹配技师，更换为SMN匹配技师
		if (companyStr.equals(CRMServiceConst.DCEC)) {
			@SuppressWarnings("unchecked")
			List<Map<String, Object>> crmEngineerQualifyMap = JSONArray
					.fromObject(httpMap.get(CRMServiceConst.CRM_REQUEST_PARAMS).toString());
			// 获取到数据之后，拆分人员数据
			for (int i = 0; i < crmEngineerQualifyMap.size(); i++) {
				Map<String, Object> crmEngineerMap = crmEngineerQualifyMap.get(i);
				String phoneNumber = crmEngineerMap.get("phone").toString();
				// 鉴权号
				String stationNo = crmEngineerMap.get("stationNo").toString();

				if (StringUtils.isEmpty(phoneNumber)){
					// 手机号为空跳过
					continue;
				}
				// 获取某个技师的资质列表
				// 通过电话号码匹配User数据
				UserT user = crmServiceDao.getUserByPhone(phoneNumber);

				@SuppressWarnings("unchecked")
				String smnListStr =  MapUtils.getString(crmEngineerMap,"SMN", "");
				if (StringUtils.isEmpty(smnListStr)){
					// 没有资质不保存
					continue;
				}
				// SF系统对&做了特殊处理，我们系统需要把它替换回来
				smnListStr = smnListStr.replace("(*)", "&");
				// 通过电话号码匹配User数据
				if (crmEngineerMap.get("requstStatus").toString().equals("1")) {// 增加
					EngineerQualifyWithsmnT engineerQualifyWithsmnT = qualifyWithsmnTMapper.selectByPhone(phoneNumber);
					int saveEngineerQualifyResult = 0;
					// 空新增，不空更新
					if (null != engineerQualifyWithsmnT){
						engineerQualifyWithsmnT.setSmnList(smnListStr);
						engineerQualifyWithsmnT.setStationNo(stationNo);
						engineerQualifyWithsmnT.setUpdator(-1L);
						engineerQualifyWithsmnT.setUpdateTime(LocalTimeUtil.getRealCurrentTime());
						saveEngineerQualifyResult = qualifyWithsmnTMapper.updateByPrimaryKeySelective(engineerQualifyWithsmnT);
					} else {
						engineerQualifyWithsmnT = new EngineerQualifyWithsmnT();
						engineerQualifyWithsmnT.setUserName(null != user ? user.getUserName() : "");
						engineerQualifyWithsmnT.setUserPhone(phoneNumber);
						engineerQualifyWithsmnT.setSmnList(smnListStr);
						engineerQualifyWithsmnT.setSource(companyStr);
						engineerQualifyWithsmnT.setCreator(-1L);
						engineerQualifyWithsmnT.setStationNo(stationNo);
						engineerQualifyWithsmnT.setCreateTime(LocalTimeUtil.getRealCurrentTime());
						saveEngineerQualifyResult = qualifyWithsmnTMapper.insertSelective(engineerQualifyWithsmnT);
					}

					if (saveEngineerQualifyResult > 0) {
						SystemLogsT systemLogsT = new SystemLogsT();
						systemLogsT.setUserId(-1);
						systemLogsT.setTname("engineerQualifyWithsmn");
						systemLogsT.setTid(engineerQualifyWithsmnT.getId());
						systemLogsT.setActionName("insertEngineerQualify");
						systemLogsT.setRemark("新增技师资质");
						loginDao.insertSystemLogs(systemLogsT);
						systemLogsT = null;
					}

				} else if (crmEngineerMap.get("requstStatus").toString().equals("2")) {// 删除
					int updateEngineerQualifyResult = qualifyWithsmnTMapper.deleteByPhone(phoneNumber);
				} else if (crmEngineerMap.get("requstStatus").toString().equals("3")) {// 修改
					EngineerQualifyWithsmnT engineerQualifyWithsmnT = qualifyWithsmnTMapper.selectByPhone(phoneNumber);
					if (null == engineerQualifyWithsmnT){
						// 若为空，则记录，并返回
						LOG.info("CRM-syncStationUserInfo修改异常：" + crmEngineerMap);
						continue;
					}
					engineerQualifyWithsmnT.setSmnList(smnListStr);
					engineerQualifyWithsmnT.setUpdator(-1L);
					engineerQualifyWithsmnT.setStationNo(stationNo);
					engineerQualifyWithsmnT.setUpdateTime(LocalTimeUtil.getRealCurrentTime());
					int updateEngineerQualifyResult = qualifyWithsmnTMapper.updateByPrimaryKeySelective(engineerQualifyWithsmnT);
					if (updateEngineerQualifyResult > 0){
						SystemLogsT systemLogsT = new SystemLogsT();
						systemLogsT.setUserId(-1);
						systemLogsT.setTname("engineerQualifyWithsmn");
						systemLogsT.setTid(engineerQualifyWithsmnT.getId());
						systemLogsT.setActionName("updateEngineerQualify");
						systemLogsT.setRemark("修改技师资质");
						loginDao.insertSystemLogs(systemLogsT);
						systemLogsT = null;
					}
				} else {// 错误状态
					LOG.info("请求状态不识别");
				}
				/**
				 * 6、返回服务站数据同步成功结果
				 */
//				JSONObject jsonObject = new JSONObject();
//				JSONObject jsonData = new JSONObject();
//				jsonObject.put("status", 0);
//				jsonObject.put("msg", "服务人员同步成功");
//				jsonObject.put("data", jsonData);
//				ParameterTool.writeResponse(response, jsonObject.toString());
			}

		} else if (companyStr.equals(CRMServiceConst.XCEC)) {
			@SuppressWarnings("unchecked")
			List<Map<String, Object>> crmEngineerQualifyMap = JSONArray
					.fromObject(httpMap.get(CRMServiceConst.CRM_REQUEST_PARAMS).toString());
			// 获取到数据之后，拆分人员数据
			for (int i = 0; i < crmEngineerQualifyMap.size(); i++) {

				Map<String, Object> crmEngineerMap = crmEngineerQualifyMap.get(i);
				String userPhone = MapUtils.getString(crmEngineerMap, "phone", "");
				if (userPhone.length() < 1) {
					// 没有同步电话号码信息
					continue;
				}
				// 获取某个技师的资质列表
				@SuppressWarnings("unchecked")
				List<Map<String, Object>> engineTypesList = (List<Map<String, Object>>) crmEngineerMap
						.get("engineTypes");
				// 通过电话号码匹配User数据
				UserT user = crmServiceDao.getUserByPhone(userPhone);
				String userName = "";
				if (user != null) {
					userName = user.getUserName();
				}
				if (engineTypesList == null || engineTypesList.size() == 0) {
					// 没有资质信息不需要保存
					continue;
				}
				// 遍历技师机型资质信息列表
				for (int j = 0; j < engineTypesList.size(); j++) {

					Map<String, Object> engineTypeMap = (Map<String, Object>) engineTypesList.get(j);
					engineTypeMap.put("phone", userPhone);
					Map<String, Object> appEngineerMap = crmServiceDao
							.getEngineerQualifyByPhoneAndTypeName(crmEngineerMap);
					if (appEngineerMap != null) {
						if (crmEngineerMap.get("requstStatus").toString().equals("1")) { // 增加

							appEngineerMap.put("SSAuthValue", engineTypeMap.get("repairScope"));
							crmServiceDao.updateEngineerQualifyByPhoneAndTypeName(appEngineerMap);
						} else if (crmEngineerMap.get("requstStatus").toString().equals("2")) { // 删除
							crmServiceDao.deleteEngineerQualifyByPhoneAndTypeName(appEngineerMap);
						} else if (crmEngineerMap.get("requstStatus").toString().equals("3")) { // 修改

							appEngineerMap.put("SSAuthValue", engineTypeMap.get("repairScope"));
							crmServiceDao.updateEngineerQualifyByPhoneAndTypeName(appEngineerMap);
						}
					} else {
						if (crmEngineerMap.get("requstStatus").toString().equals("1")) { // 增加
							List<Long> engineTypeIds = crmServiceDao
									.getEngineTypeIDByTypeName(engineTypeMap.get("engineType").toString());
							String engineerTypeName = engineTypeMap.get("engineType").toString();
							String SSAuthName = engineTypeMap.get("repairScope").toString();

							Map<String, Object> engineerQualifyMap = new HashedMap<String, Object>();
							engineerQualifyMap.put("UserPhone", userPhone);
							if (engineTypeIds != null && engineTypeIds.size() > 0) {
								engineerQualifyMap.put("EngineTypeId", engineTypeIds.get(0));
							} else {
								continue;
							}
							if (userName.length() > 0) {
								engineerQualifyMap.put("UserName", user.getUserName());
							}
							engineerQualifyMap.put("engineerId", -1);
							engineerQualifyMap.put("Flag", 0);
							engineerQualifyMap.put("Creator", -1);
							engineerQualifyMap.put("CreateTime", LocalTimeUtil.getRealCurrentTime());
							engineerQualifyMap.put("EngineTypeName", engineerTypeName);
							engineerQualifyMap.put("SSAuthValue", SSAuthName);

							crmServiceDao.insertEngineerQualify_T(engineerQualifyMap);
						} else if (crmEngineerMap.get("requstStatus").toString().equals("2")) { // 删除

						} else if (crmEngineerMap.get("requstStatus").toString().equals("3")) { // 修改

							List<Long> engineTypeIds = crmServiceDao
									.getEngineTypeIDByTypeName(engineTypeMap.get("engineType").toString());
							String engineerTypeName = engineTypeMap.get("engineType").toString();
							String SSAuthName = engineTypeMap.get("repairScope").toString();

							List<Map<String, Object>> engineerList = crmServiceDao
									.getEngineerQualifyByPhoneAndEngineName(engineerTypeName, userPhone);
							if (engineerList == null || engineerList.size() < 1) { // 插入
								Map<String, Object> engineerQualifyMap = new HashedMap<String, Object>();
								engineerQualifyMap.put("UserPhone", userPhone);
								if (engineTypeIds != null && engineTypeIds.size() > 0) {
									engineerQualifyMap.put("EngineTypeId", engineTypeIds.get(0));
								}
								if (userName.length() > 0) {
									engineerQualifyMap.put("UserName", user.getUserName());
								}
								engineerQualifyMap.put("Flag", 0);
								engineerQualifyMap.put("Creator", -1);
								engineerQualifyMap.put("CreateTime", LocalTimeUtil.getRealCurrentTime());
								engineerQualifyMap.put("Updator", -1);
								engineerQualifyMap.put("UpdateTime", LocalTimeUtil.getRealCurrentTime());
								engineerQualifyMap.put("EngineTypeName", engineerTypeName);
								engineerQualifyMap.put("SSAuthValue", SSAuthName);
								crmServiceDao.insertEngineerQualify_T(engineerQualifyMap);
							} else {
								for (Map<String, Object> map : engineerList) {
									map.put("Updator", -1);
									map.put("UpdateTime", LocalTimeUtil.getRealCurrentTime());
									crmServiceDao.updateEngineerQualifyByPhoneAndEngineName(map);
								}
							}

						}
					}
				}

				/**
				 * 6、返回服务站数据同步成功结果
				 */
//				JSONObject jsonObject = new JSONObject();
//				JSONObject jsonData = new JSONObject();
//				jsonObject.put("status", 0);
//				jsonObject.put("msg", "服务人员同步成功");
//				jsonObject.put("data", jsonData);
//				ParameterTool.writeResponse(response, jsonObject.toString());

			}
		}
		JSONObject jsonObject = new JSONObject();
		JSONObject jsonData = new JSONObject();
		jsonObject.put("status", 0);
		jsonObject.put("msg", "服务人员同步成功");
		jsonObject.put("data", jsonData);
		ParameterTool.writeResponse(response, jsonObject.toString());
		return null;
	}

	@Transactional
	@Override
	@SuppressWarnings("unchecked")
	public ModelAndView syncPositionInfo(Map<String, Object> httpMap) {
		HttpServletResponse response = (HttpServletResponse) httpMap.get("response");
		String companyStr = httpMap.get("company").toString();

		// 1.获取企业信息
		CompanyT channelCompany = companyTDao.getCompanyInfoByCompanyNo(companyStr);
		if (null == channelCompany) {
			ParameterTool.writeResponse(response, 1, "区域管辖信息同步失败，渠道信息为空");
			return null;
		}
		// 2.岗位列表
		List<Map<String, Object>> crmPositionInfoList = JSONArray
				.fromObject(httpMap.get(CRMServiceConst.CRM_REQUEST_PARAMS).toString());
		if (CollectionUtils.isEmpty(crmPositionInfoList)) {
			ParameterTool.writeResponse(response, 1, "区域管辖信息同步失败，列表数据为空");
			return null;
		}

		if (companyStr.equals(CRMServiceConst.DCEC)) {
			// 循环岗位信息
			for (int i = 0; i < crmPositionInfoList.size(); i++) {
				// 获取岗位信息
				Map<String, Object> crmPositionMap = crmPositionInfoList.get(i);
				// 获取企业信息
				String companyNo = crmPositionMap.get("company").toString();
				CompanyT company = companyTDao.getCompanyInfoByCompanyNo(companyNo);
				if (company == null) {

					APIExceptionT crmApiException = new APIExceptionT();
					crmApiException.setAPIName("synPositionInfo");
					crmApiException.setCompanyNo(companyNo);
					crmApiException.setData(crmPositionMap.toString());
					crmApiException.setDirection(0);
					crmApiException.setExceptionInfo("企业编号：" + companyNo + "，企业数据未同步到APP系统");
					crmApiException.setFlag(0);
					crmApiException.setSystemTime(LocalTimeUtil.getRealCurrentTime());
					crmServiceDao.saveExceptionToExpTable(crmApiException);
					continue;
				}
				// 获取企业id
				long companyId = company.getId();
				crmPositionMap.put("CompanyID", companyId);
				// 转化成app postion table需要的字段参数
				Map<String, Object> appPositionMap = CRMRequestMapToAppMapUtils.toPositionInfoMap(crmPositionMap);
				if (appPositionMap == null)
					continue;
				// 根据positinNo和creator查询是否已经存在记录
				Map<String, Object> positionMap = crmServiceDao
						.getPositionInfoToTableByCrmPostNoAndCreator(appPositionMap);// 理论上这里只能查询到一条数据（一个crmPositionNo+level+flag只能查询到一条数据），但这里会存在多条数据，需要通过excel对比出相同数据进行手动处理
				if (appPositionMap.get("Status").toString().equals("1")) {// 新增
					if (positionMap == null) {
						crmServiceDao.savePositionInfoToTable(appPositionMap);
					} else {
						appPositionMap.put("positionId", positionMap.get("ID"));
					}
				} else if (appPositionMap.get("Status").toString().equals("3")) {// 修改
					if (positionMap == null) {
						crmServiceDao.savePositionInfoToTable(appPositionMap);
					} else {
						crmServiceDao.updatePositionInfoToTable(appPositionMap);
					}

				} else if (appPositionMap.get("Status").toString().equals("2")) {// 删除
					if (positionMap == null) {

					} else {
						crmServiceDao.deletePositionInfoToTable(appPositionMap);
					}
				} else { // 新增
					LOG.info("请求类型传递不正确");
					continue;
				}

				// 2、服务站列表
				@SuppressWarnings("unchecked")
				List<Map<String, Object>> crmPositionStationsMap = (List<Map<String, Object>>) crmPositionMap
						.get("stations");
				if (crmPositionStationsMap == null || crmPositionStationsMap.size() == 0) {
					LOG.info("服务站列表为空");
					crmPositionStationsMap = null;
					continue;
				}
				// 2.1将服务站列表转化为ssrepair list
				List<Map<String, Object>> repairList = new ArrayList<Map<String, Object>>();
				for (int k = 0; k < crmPositionStationsMap.size(); k++) {
					Map<String, Object> crmPositionStationMap = (Map<String, Object>) crmPositionStationsMap.get(k);
					crmPositionStationMap.put("CompanyID", companyId);
					List<SSRepairT> repairTModelList = serviceStationDao
							.getSSRepairByCompanyIDAndBusinessNo(crmPositionStationMap);//理论上只能查询到一条（因为同一个渠道的授权是一对一关系）
					// 根据station和company，没有找到对应的服务站信息
					if (repairTModelList == null || repairTModelList.size() == 0) {

						APIExceptionT crmApiException = new APIExceptionT();
						crmApiException.setAPIName("synPositionInfo");
						crmApiException.setCompanyNo(companyNo);
						crmApiException.setData(crmPositionStationMap.toString());
						crmApiException.setDirection(0);
						crmApiException.setExceptionInfo(
								"服务站编号：" + crmPositionStationMap.get("stationNo") + "，服务站数据未同步到APP系统");
						crmApiException.setFlag(0);
						crmApiException.setSystemTime(LocalTimeUtil.getRealCurrentTime());

						crmServiceDao.saveExceptionToExpTable(crmApiException);
						//continue;

						JSONObject jsonObject = new JSONObject();
						jsonObject.put("status", 1000);
						jsonObject.put("msg", "请先同步授权的服务站");
						jsonObject.put("data", null);
						ParameterTool.writeResponse(response, jsonObject.toString());
						return null;
					}
					for (int j = 0; j < repairTModelList.size(); j++) {
						Map<String, Object> repairMap = new HashedMap<String, Object>();
						repairMap.put("repair", repairTModelList.get(j));
						repairMap.put("Status", crmPositionStationMap.get("requstStatus").toString());
						repairList.add(repairMap);
					}

				}

				// 3、联系人列表
				@SuppressWarnings("unchecked")
				List<Map<String, Object>> crmPositionContactInfosMap = (List<Map<String, Object>>) crmPositionMap
						.get("contactInfos");
				// 联系人列表为空
				if (crmPositionContactInfosMap == null || crmPositionContactInfosMap.size() == 0) {
					crmPositionContactInfosMap = null;
					continue;
				}
				// 没有获取positionId数据
				if (appPositionMap.get("positionId").toString().equals("-1")) {
					crmPositionContactInfosMap = null;
					continue;
				}
				if (crmPositionContactInfosMap != null && crmPositionContactInfosMap.size() > 0) {
					for (int z = 0; z < crmPositionContactInfosMap.size(); z++) {
						// 联系人信息详情Map
						Map<String, Object> crmPositionContanctMap = crmPositionContactInfosMap.get(z);
						crmPositionContanctMap.put("Creator", companyId);//需要将企业编号放进去
						crmPositionContanctMap.put("positionId", appPositionMap.get("positionId"));
						String phoneNumber = crmPositionContanctMap.get("phone").toString();
						if (phoneNumber == null || phoneNumber.length() < 1) {

							APIExceptionT crmApiException = new APIExceptionT();
							crmApiException.setAPIName("synPositionInfo");
							crmApiException.setCompanyNo(companyNo);
							crmApiException.setData(crmPositionContanctMap.toString());
							crmApiException.setDirection(0);
							crmApiException.setExceptionInfo("服务站人员电话号码为空");
							crmApiException.setFlag(0);
							crmApiException.setSystemTime(LocalTimeUtil.getRealCurrentTime());
							crmServiceDao.saveExceptionToExpTable(crmApiException);
							continue;
						}
						// 通过电话号码匹配User数据
						UserT user = crmServiceDao.getUserByPhone(phoneNumber);
						if (user == null) {
							APIExceptionT crmApiException = new APIExceptionT();
							crmApiException.setAPIName("synPositionInfo");
							crmApiException.setCompanyNo(companyNo);
							crmApiException.setData(crmPositionContanctMap.toString());
							crmApiException.setDirection(0);
							crmApiException.setExceptionInfo("人员账户在APP系统未创建，电话号码:" + phoneNumber);
							crmApiException.setFlag(0);
							crmApiException.setSystemTime(LocalTimeUtil.getRealCurrentTime());
							crmServiceDao.saveExceptionToExpTable(crmApiException);

							JSONObject jsonObject = new JSONObject();
							jsonObject.put("status", 1000);
							jsonObject.put("msg", "请现在APP中注册手机号");
							jsonObject.put("data", null);
							ParameterTool.writeResponse(response, jsonObject.toString());
							return null;
						} else {
							crmPositionContanctMap.put("userId", user.getId());
						}
						// 接收postUserID
						long postUserId = -1;
						Map<String, Object> appPositionContactMap = CRMRequestMapToAppMapUtils
								.toPositionContactInfoMap(crmPositionContanctMap);
						if (appPositionContactMap == null)
							continue;
						Map<String, Object> positionUserMap = crmServiceDao
								.getPositionUserInfoByCrmPositionIDAndPhoneANDCreatorOrder(appPositionContactMap);
						if (appPositionContactMap.get("Status").toString().equals("1")) {// 新增
							if (positionUserMap == null) {
								crmServiceDao.savePositionContactToTable(appPositionContactMap);
								Number postUserNum = (Number) appPositionContactMap.get("positionUserID");
								postUserId = postUserNum.longValue();
							} else {
								postUserId = MapUtils.getIntValue(positionUserMap, "ID", -1);
							}

						} else if (appPositionContactMap.get("Status").toString().equals("3")) {// 修改
							if (positionUserMap == null) {
								//先删除旧的区域下 区域和管辖人的关系
								if (appPositionContactMap.containsKey("PositionID") && null != appPositionContactMap.get("PositionID")) {
									appPositionContactMap.put("DeleteTime", LocalTimeUtil.getRealCurrentTime());
									appPositionContactMap.put("Deleter", companyId);
									int deletePositionContactToTableDcec = crmServiceDao.deletePositionContactToTableDcec(appPositionContactMap);
									if (deletePositionContactToTableDcec > 0) {
										LOG.error("旧的区域管辖删除成功，CRMPlatformServiceImpl   3315");
									} else {
										LOG.error("旧的区域管辖删除失败，CRMPlatformServiceImpl   3316");
									}
									appPositionContactMap.remove("DeleteTime");
									appPositionContactMap.remove("Deleter");
								}
								//添加新的管辖关系
								crmServiceDao.savePositionContactToTable(appPositionContactMap);
								Number postUserNum = (Number) appPositionContactMap.get("positionUserID");
								postUserId = postUserNum.longValue();
							} else {
								crmServiceDao.updatePositionContactToTableOrder(appPositionContactMap);
								Number postUserNum = (Number) appPositionContactMap.get("positionUserID");
								postUserId = postUserNum.longValue();
							}

						} else if (appPositionContactMap.get("Status").toString().equals("2")) {// 删除
							if (positionUserMap == null) {// 既然是删除就不创建了

							} else {
								crmServiceDao.deletePositionContactToTable(appPositionContactMap);
								Number postUserNum = (Number) appPositionContactMap.get("positionUserID");
								postUserId = postUserNum.longValue();
							}

						}
						// 没有对应的positionUserID数据
						if (String.valueOf(postUserId).equals("-1")) {
							continue;
						}

						if (repairList.size() > 0) {
							for (int k = 0; k < repairList.size(); k++) {
								Map<String, Object> repairMap = repairList.get(k);
								Map<String, Object> userServiceMap = CRMRequestMapToAppMapUtils
										.toPositionUserServiceMap((SSRepairT) repairMap.get("repair"), postUserId,
												repairMap.get("Status").toString(), companyId);
								Map<String, Object> positionUserServiceStationMap = crmServiceDao
										.getPositionUserServiceStationInfoByServiceStationNoAndCompanyIDANDPositionID(
												userServiceMap);
								if (userServiceMap.get("Status").toString().equals("1")) {// 新增
									if (positionUserServiceStationMap == null) {
										crmServiceDao.savePositionUserServiceStationToTable(userServiceMap);
									}
								} else if (userServiceMap.get("Status").toString().equals("3")) {// 修改
									if (positionUserServiceStationMap == null) {
										//将旧的  服务站和 区域经理的 关系删除， 添加新的
										if (userServiceMap.containsKey("ServiceStationNo") && null != userServiceMap.get("ServiceStationNo")) {
											//  商务处主任   在一个区域  position 中 会有一条数据  且 level 为2   同样在 positionuser 会存在一条
											//  在PositionUserServiceStation_T 存在 多条
											//区域经理   在一个区域   position 中 会有一条数据  且 level 为1   同样在 positionuser 会存在一条
											//											//  在PositionUserServiceStation_T 存在 多条
											String level = MapUtils.getString(appPositionMap, "Level");
                                            String ServiceStationNo = MapUtils.getString(userServiceMap, "ServiceStationNo");
											List<Long> positionUserIds = crmServiceDao.listByStationNoAndLevel(level, ServiceStationNo);
											if (com.cci.kangdao.utilTool.CollectionUtils.isNotEmpty(positionUserIds)) {
												//删除 旧的区域经理和服务站的关系
												for (Long positionUserId : positionUserIds) {
													userServiceMap.put("PositionUserID", positionUserId);
                                                    userServiceMap.put("DeleteTime", LocalTimeUtil.getRealCurrentTime());
                                                    userServiceMap.put("Deleter", companyId);
                                                    userServiceMap.put("Flag", -1);
                                                    int deletePositionUserServiceStationToTable = crmServiceDao.deletePositionUserServiceStationToTable(userServiceMap);
                                                    if (deletePositionUserServiceStationToTable > 0) {
                                                        LOG.error("将旧的服务站和区域经理的关系删除成功，CRMPlatformServiceImpl   3381");
                                                    } else {
                                                        LOG.error("将旧的服务站和区域经理的关系删除失败，CRMPlatformServiceImpl   3383");
                                                    }
												}
												//恢复以前的数据
												userServiceMap.put("PositionUserID", postUserId);
                                                userServiceMap.remove("DeleteTime");
                                                userServiceMap.remove("Deleter");
                                                userServiceMap.remove("Flag");
											}
//											int deletePositionUserServiceStationByChannelAndStationNo = crmServiceDao.deletePositionUserServiceStationByChannelAndStationNo(userServiceMap);

										}
										crmServiceDao.savePositionUserServiceStationToTable(userServiceMap);
									} else {
										crmServiceDao.updatePositionUserServiceStationToTable(userServiceMap);
									}

								} else if (userServiceMap.get("Status").toString().equals("2")) {// 删除
									if (positionUserServiceStationMap == null) {

									} else {
										crmServiceDao.deletePositionUserServiceStationToTable(userServiceMap);
									}

								}
							}
						}

					}

				}

			}
			JSONObject jsonData = new JSONObject();
			JSONObject jsonObject = new JSONObject();
			jsonObject.put("status", 0);
			jsonObject.put("msg", "区域管辖信息同步成功");
			jsonObject.put("data", jsonData);
			ParameterTool.writeResponse(response, jsonObject.toString());
		} else if (companyStr.equals(CRMServiceConst.DBU)) {
			//3.4.0需求: 由于dbu派工表变更，之前逻辑全部变更为新的
			// 循环职位信息
			for (int i = 0; i < crmPositionInfoList.size(); i++) {
				// 获取岗位信息
				Map<String, Object> crmPositionMap = crmPositionInfoList.get(i);
				// 获取企业信息
				CompanyT company = companyTDao.getCompanyInfoByCompanyNo(companyStr);
				// 获取企业id
				long companyId = company.getId();
				crmPositionMap.put("CompanyID", companyId);
				// 转化成app postion table需要的字段参数
				Map<String, Object> appPositionMap = CRMRequestMapToAppMapUtils.toDBUPositionInfoMap(crmPositionMap);
				if (appPositionMap == null)
					continue;

				// 根据positinNo和creator查询是否已经存在记录
				Map<String, Object> positionMap = crmServiceDao
						.getPositionInfoToTableByCrmPostNoAndCreator(appPositionMap);//查询是否有相同的职位信息
				if (appPositionMap.get("Status").toString().equals("1")) {// 新增
					if (positionMap == null) {
						crmServiceDao.savePositionInfoToTable(appPositionMap);
					} else {
						appPositionMap.put("positionId", positionMap.get("ID"));
					}
				} else if (appPositionMap.get("Status").toString().equals("3")) {// 修改
					if (positionMap == null) {
						crmServiceDao.savePositionInfoToTable(appPositionMap);
					} else {
						crmServiceDao.updatePositionInfoToTable(appPositionMap);
					}

				} else if (appPositionMap.get("Status").toString().equals("2")) {// 删除
					if (positionMap == null) {

					} else {
						//crmServiceDao.deletePositionInfoToTable(appPositionMap);//删除职位
						crmServiceDao.deletePositionUserInfoToTable(appPositionMap);//删除职位与人员关联表关系
						crmServiceDao.deletePositionUserServiceStationInfo(appPositionMap);//删除人员与服务站关联表关系
					}
				} else { // 新增
					LOG.info("请求类型传递不正确");
					continue;
				}


//                List<Map<String, Object>> crmPositionContactInfosMap = (List<Map<String, Object>>) crmPositionMap
//                        .get("contactInfos");
				// 2、区域工程师信息
				crmPositionMap.put("positionId", appPositionMap.get("positionId"));
				Map<String, Object> appPositionContactMap = CRMRequestMapToAppMapUtils
						.toPositionContactInfo(crmPositionMap);
				// 联系人列表为空
				if (appPositionContactMap == null || appPositionContactMap.size() == 0) {
					appPositionContactMap = null;
					continue;
				}
				// 没有获取到positionId数据
				if (appPositionMap.get("positionId").toString().equals("-1")) {
					appPositionContactMap = null;
					continue;
				}

				if (appPositionContactMap.size() != 0) {

					// 联系人信息详情Map
//                    Map<String, Object> crmPositionContanctMap = crmPositionContactInfosMap.get(z);
//                    crmPositionContanctMap.put("Creator", companyId);//需要将企业编号放进去
//                    crmPositionContanctMap.put("positionId", appPositionMap.get("positionId"));

					String phoneNumber = crmPositionMap.get("phone").toString();
					if (phoneNumber == null || phoneNumber.length() < 1) {

						APIExceptionT crmApiException = new APIExceptionT();
						crmApiException.setAPIName("synPositionInfo");
						crmApiException.setCompanyNo(companyStr);
						crmApiException.setData(appPositionContactMap.toString());
						crmApiException.setDirection(0);
						crmApiException.setExceptionInfo("服务站人员电话号码为空");
						crmApiException.setFlag(0);
						crmApiException.setSystemTime(LocalTimeUtil.getRealCurrentTime());
						crmServiceDao.saveExceptionToExpTable(crmApiException);
						LOG.info("用户不存在");
						ParameterTool.writeErrorResponse(response, -1, "该用户不存在于ecummins："+crmPositionMap.get("contactName"));
						return null;
					}
					// 通过电话号码匹配User数据
					UserT user = crmServiceDao.getUserByPhone(phoneNumber);//查询User_T表中的人员
					if (user == null) {
						APIExceptionT crmApiException = new APIExceptionT();
						crmApiException.setAPIName("synPositionInfo");
						crmApiException.setCompanyNo(companyStr);
						crmApiException.setData(appPositionContactMap.toString());
						crmApiException.setDirection(0);
						crmApiException.setExceptionInfo("人员账户在APP系统未创建，电话号码:" + phoneNumber);
						crmApiException.setFlag(0);
						crmApiException.setSystemTime(LocalTimeUtil.getRealCurrentTime());
						crmServiceDao.saveExceptionToExpTable(crmApiException);

					} else {
						appPositionContactMap.put("UserID", user.getId());
					}
					// 接收postUserID
					long postUserId = -1;
//                    Map<String, Object> positionContactInfoMap = CRMRequestMapToAppMapUtils
//                            .toPositionContactInfoMap(appPositionContactMap);
					if (appPositionContactMap.size()==0)
						continue;

					Map<String, Object> positionUserMap = crmServiceDao
							.getPositionUserInfoByCrmPositionIDAndPhoneANDCreatorDbu(appPositionContactMap);
					if (appPositionContactMap.get("Status").toString().equals("1")) {// 新增
						if (positionUserMap == null) {
							crmServiceDao.savePositionContactToTable(appPositionContactMap);
							Number postUserNum = (Number) appPositionContactMap.get("positionUserID");
							postUserId = postUserNum.longValue();
						} else {
							postUserId = MapUtils.getIntValue(positionUserMap, "ID", -1);
						}

					} else if (appPositionContactMap.get("Status").toString().equals("3")) {// 修改
						if (positionUserMap == null) {
							crmServiceDao.savePositionContactToTable(appPositionContactMap);
							Number postUserNum = (Number) appPositionContactMap.get("positionUserID");
							postUserId = postUserNum.longValue();
						} else {
							crmServiceDao.updatePositionContactToTableDbu(appPositionContactMap);
							Number postUserNum = (Number) appPositionContactMap.get("positionUserID");
							postUserId = postUserNum.longValue();
						}

					} else if (appPositionContactMap.get("Status").toString().equals("2")) {// 删除
						if (positionUserMap == null) {// 既然是删除就不创建了

						} else {
							crmServiceDao.deletePositionContactToTableDbu(appPositionContactMap);
							Number postUserNum = (Number) appPositionContactMap.get("positionUserID");
							postUserId = postUserNum.longValue();
						}

					}
					// 没有对应的positionUserID数据
					if (String.valueOf(postUserId).equals("-1")) {
						continue;
					}

					// 3、获取服务站列表后添加服务站关系，这一步不需要关心服务站是否存在，服务站同步的数据在syncStationInfo接口已经同步完毕后才进行该接口的调用
					//但会存在服务站列表中stationNo为空的情况，此时抛给crm异常信息即可
					List<Map<String, Object>> crmPositionStationsMap = (List<Map<String, Object>>) crmPositionMap
							.get("stations");//获取服务站List
					if (crmPositionStationsMap == null || crmPositionStationsMap.size() == 0) {
						LOG.info("服务站列表为空");
						continue;
					}
					// DBU的分公司信息需要管理在区域工程师下面
//                    Map<String, Object> positionStationMap = new HashMap<>();
//                    if (StringUtils.isEmpty(MapUtils.getString(crmPositionMap, "stationNo"))) {
//                        LOG.info("stationNo为空");
//                        ParameterTool.writeErrorResponse(response, -1, "stationNo为空");
//                        return null;
//                    } else {
//                        positionStationMap.put("stationNo", crmPositionMap.get("stationNo"));
//                    }
//
//                    positionStationMap.put("requstStatus", crmPositionMap.get("requstStatus"));
//                    crmPositionStationsMap.add(positionStationMap);

					// 3.1将服务站列表转化为ssrepair list
					List<Map<String, Object>> repairList = new ArrayList<Map<String, Object>>();
					for (int k = 0; k < crmPositionStationsMap.size(); k++) {
						Map<String, Object> crmPositionStationMap = (Map<String, Object>) crmPositionStationsMap.get(k);
						crmPositionStationMap.put("CompanyID", companyId);
						if (StringUtils.isEmpty(MapUtils.getString(crmPositionStationMap, "stationNo"))) {
							LOG.info("stationNo为空");
							ParameterTool.writeErrorResponse(response, -1, "stationNo为空");
							return null;
						}
						List<SSRepairT> repairTModelList = serviceStationDao
								.getSSRepairByCompanyIDAndBusinessNo(crmPositionStationMap);
						// 根据station和company，没有找到对应的服务站信息，如果服务站状态是删除状态，不需验证授权信息要
						if (repairTModelList == null || repairTModelList.size() == 0) {

							APIExceptionT crmApiException = new APIExceptionT();
							crmApiException.setAPIName("synPositionInfo");
							crmApiException.setCompanyNo(companyStr);
							crmApiException.setData(crmPositionStationMap.toString());
							crmApiException.setDirection(0);
							crmApiException.setExceptionInfo(
									"服务站编号：" + crmPositionStationMap.get("stationNo") + "，服务站数据未同步到APP系统");
							crmApiException.setFlag(0);
							crmApiException.setSystemTime(LocalTimeUtil.getRealCurrentTime());
							crmServiceDao.saveExceptionToExpTable(crmApiException);
							LOG.info("服务站编号：" + crmPositionStationMap.get("stationNo") + "，服务站数据未同步到APP系统");
							ParameterTool.writeErrorResponse(response, -1, "服务站编号：" + crmPositionStationMap.get("stationNo") + "，服务站数据未同步到APP系统");
							return null;
						}
						for (int j = 0; j < repairTModelList.size(); j++) {
							Map<String, Object> repairMap = new HashedMap<String, Object>();
							repairMap.put("repair", repairTModelList.get(j));
							repairMap.put("Status", crmPositionStationMap.get("requstStatus").toString());
							repairList.add(repairMap);
						}
					}
					if (repairList.size() > 0) {
						for (int k = 0; k < repairList.size(); k++) {
							Map<String, Object> repairMap = repairList.get(k);
							Map<String, Object> userServiceMap = CRMRequestMapToAppMapUtils
									.toPositionUserServiceMap((SSRepairT) repairMap.get("repair"), postUserId,
											repairMap.get("Status").toString(), companyId);
							Map<String, Object> positionUserServiceStationMap = crmServiceDao
									.getPositionUserServiceStationInfoByServiceStationNoAndCompanyIDANDPositionID(
											userServiceMap);
							if (userServiceMap.get("Status").toString().equals("1")) {// 新增
								if (positionUserServiceStationMap == null) {
									crmServiceDao.savePositionUserServiceStationToTable(userServiceMap);
								}
							}  else if (userServiceMap.get("Status").toString().equals("2")) {// 删除
								if (positionUserServiceStationMap == null) {

								} else {
									crmServiceDao.deletePositionUserServiceStationToTable(userServiceMap);
								}
							}
						}
					}
				}
			}
			JSONObject jsonData = new JSONObject();
			JSONObject jsonObject = new JSONObject();
			jsonObject.put("status", 0);
			jsonObject.put("msg", "区域管辖信息同步成功");
			jsonObject.put("data", jsonData);
			ParameterTool.writeResponse(response, jsonObject.toString());

		} else if (companyStr.equals(CRMServiceConst.XCEC)) {

			// 获取企业信息
			CompanyT company = companyTDao.getCompanyInfoByCompanyNo(companyStr);
			// 获取企业id
			long companyId = company.getId();
			// 批量删除XCEC岗位信息
			crmServiceDao.deletePositionByCompanyId(companyId);
			// 循环岗位信息
			for (int i = 0; i < crmPositionInfoList.size(); i++) {
				// 获取岗位信息
				Map<String, Object> crmPositionMap = crmPositionInfoList.get(i);

				if (company == null) {
					this.saveToAPIExceptionT("synPositionInfo", "企业编号：" + companyStr + "，企业数据未同步到APP系统",
							crmPositionMap.toString(), companyStr);
				}
				crmPositionMap.put("CompanyID", companyId);
				// 转化成app postion table需要的字段参数
				Map<String, Object> appPositionMap = CRMRequestMapToAppMapUtils.toXCECPositionInfoMap(crmPositionMap);
				if (appPositionMap == null)
					continue;
				// 根据positinNo和creator查询是否已经存在记录
				//				Map<String,Object> positionMap = crmServiceDao.getPositionInfoToTableByCrmPostNoAndCreator(appPositionMap);
				crmServiceDao.savePositionInfoToTable(appPositionMap);

				// 2、服务站列表
				@SuppressWarnings("unchecked")
				List<Map<String, Object>> crmPositionStationsMap = (List<Map<String, Object>>) crmPositionMap
						.get("stations");
				if (crmPositionStationsMap == null || crmPositionStationsMap.size() == 0) {
					LOG.info("服务站列表为空");
					crmPositionStationsMap = null;
					continue;
				}
				// 2.1将服务站列表转化为ssrepair list
				List<Map<String, Object>> repairList = new ArrayList<Map<String, Object>>();
				for (int k = 0; k < crmPositionStationsMap.size(); k++) {
					Map<String, Object> crmPositionStationMap = (Map<String, Object>) crmPositionStationsMap.get(k);
					crmPositionStationMap.put("CompanyID", companyId);
					List<SSRepairT> repairTModelList = serviceStationDao
							.getSSRepairByCompanyIDAndBusinessNo(crmPositionStationMap);
					// 根据station和company，没有找到对应的服务站信息
					if (repairTModelList == null || repairTModelList.size() == 0) {

						this.saveToAPIExceptionT("synPositionInfo",
								"服务站编号：" + crmPositionStationMap.get("stationNo") + "，服务站数据未同步到APP系统",
								crmPositionStationMap.toString(), companyStr);
						continue;
					}
					for (int j = 0; j < repairTModelList.size(); j++) {
						Map<String, Object> repairMap = new HashedMap<String, Object>();
						repairMap.put("repair", repairTModelList.get(j));
						repairMap.put("Status", 1);
						repairList.add(repairMap);
					}

				}

				// 3、联系人列表
				@SuppressWarnings("unchecked")
				List<Map<String, Object>> crmPositionContactInfosMap = (List<Map<String, Object>>) crmPositionMap
						.get("contactInfos");
				// 联系人列表为空
				if (crmPositionContactInfosMap == null || crmPositionContactInfosMap.size() == 0) {
					crmPositionContactInfosMap = null;
					continue;
				}
				// 没有获取positionId数据
				if (appPositionMap.get("positionId").toString().equals("-1")) {
					crmPositionContactInfosMap = null;
					continue;
				}
				if (crmPositionContactInfosMap != null && crmPositionContactInfosMap.size() > 0) {
					for (int z = 0; z < crmPositionContactInfosMap.size(); z++) {
						// 联系人信息详情Map
						Map<String, Object> crmPositionContanctMap = crmPositionContactInfosMap.get(z);
						crmPositionContanctMap.put("Creator", companyId);//需要将企业编号放进去
						crmPositionContanctMap.put("positionId", appPositionMap.get("positionId"));
						String phoneNumber = crmPositionContanctMap.get("phone").toString();
						if (phoneNumber == null || phoneNumber.length() < 1) {

							this.saveToAPIExceptionT("synPositionInfo", "服务站人员电话号码为空",
									crmPositionContanctMap.toString(), companyStr);

							continue;
						}
						// 通过电话号码匹配User数据
						UserT user = crmServiceDao.getUserByPhone(phoneNumber);
						if (user == null) {

							this.saveToAPIExceptionT("synPositionInfo", "人员账户在APP系统未创建，电话号码:" + phoneNumber,
									crmPositionContanctMap.toString(), companyStr);

						} else {
							crmPositionContanctMap.put("userId", user.getId());
						}
						// 接收postUserID
						long postUserId = -1;
						Map<String, Object> appPositionContactMap = CRMRequestMapToAppMapUtils
								.toXCECPositionContactInfoMap(crmPositionContanctMap);
						if (appPositionContactMap == null)
							continue;
						//						Map<String,Object> positionUserMap = crmServiceDao.getPositionUserInfoByCrmPostionIDAndPhoneANDCreator(appPositionContactMap);
						crmServiceDao.savePositionContactToTable(appPositionContactMap);
						Number postUserNum = (Number) appPositionContactMap.get("positionUserID");
						postUserId = postUserNum.longValue();
						// 没有对应的positionUserID数据
						if (String.valueOf(postUserId).equals("-1")) {
							continue;
						}

						if (repairList.size() > 0) {
							for (int k = 0; k < repairList.size(); k++) {
								Map<String, Object> repairMap = repairList.get(k);
								Map<String, Object> userServiceMap = CRMRequestMapToAppMapUtils
										.toXCECPositionUserServiceMap((SSRepairT) repairMap.get("repair"), postUserId,
												repairMap.get("Status").toString(), companyId);
								//								Map<String,Object> positionUserServiceStationMap = crmServiceDao.getPositionUserServiceStationInfoByServiceStationNoAndCompanyIDANDPositionID(userServiceMap);
								crmServiceDao.savePositionUserServiceStationToTable(userServiceMap);
							}
						}

					}

				}

			}
			JSONObject jsonData = new JSONObject();
			JSONObject jsonObject = new JSONObject();
			jsonObject.put("status", 0);
			jsonObject.put("msg", "区域管辖信息同步成功");
			jsonObject.put("data", jsonData);
			ParameterTool.writeResponse(response, jsonObject.toString());
		} else if (companyStr.equals(CRMServiceConst.CCEC)) {
			// 获取企业id
			long companyId = channelCompany.getId();
			try {
				String currentTime = LocalTimeUtil.getRealCurrentTime();
				Map<String, Long> serviceStationIdMap = new HashMap<>();
				for (Map<String, Object> crmPositionMap : crmPositionInfoList) {
					// 处理position信息
					Long positionId = null;
					String positionName = MapUtils.getString(crmPositionMap, "position");
					Integer level = MapUtils.getInteger(crmPositionMap, "level", 1);
					Map<String, Object> queryPositionMap = new HashMap<>(2);
					queryPositionMap.put("CrmPostNo", positionName);
					queryPositionMap.put("Level", level);
					queryPositionMap.put("Creator", channelCompany.getId());
					Map<String, Object> positionMap = crmServiceDao
							.getPositionInfoToTableByCrmPostNoAndCreator(queryPositionMap);
					if (MapUtils.isEmpty(positionMap)) {
						Map<String, Object> savePositionMap = new HashMap<>();
						savePositionMap.put("CrmPostNo", positionName);
						savePositionMap.put("CrmPositionName", positionName);
						savePositionMap.put("AppPositionName", positionName);
						savePositionMap.put("Level", level);
						savePositionMap.put("Creator", companyId);
						savePositionMap.put("CreateTime", LocalTimeUtil.getRealCurrentTime());
						crmServiceDao.savePositionInfoToTable(savePositionMap);
						positionId = MapUtils.getLong(savePositionMap, "positionId");
					} else {
						positionId = MapUtils.getLong(positionMap, "ID");
					}
					String requestStatus = MapUtils.getString(crmPositionMap, "requstStatus");
					String phone = MapUtils.getString(crmPositionMap, "phone");
					Map<String, Object> queryPositionUserMap = new HashMap<>();
					queryPositionUserMap.put("UserPhone", phone);
					queryPositionUserMap.put("PositionID", positionId);
					Map<String, Object> positionUserMap = crmServiceDao
							.getPositionUserInfoByCrmPositionIDAndPhoneANDCreatorOrder(queryPositionUserMap);
					// 删除逻辑
					if (requestStatus.equals("2")) {
						if (MapUtils.isEmpty(positionUserMap)) {
							LOG.warn("删除区域管辖，用户职位信息不存在，无法删除。用户手机号：" + phone);
						}

						// 删除PositionUser表数据
						Map<String, Object> deletePositionUserMap = new HashMap<>(4);
						deletePositionUserMap.put("UserPhone", phone);
						deletePositionUserMap.put("PositionID", positionId);
						deletePositionUserMap.put("Flag", -1);
						deletePositionUserMap.put("Deleter", channelCompany.getId());
						deletePositionUserMap.put("DeleteTime", currentTime);
						crmServiceDao.deletePositionContactToTable(deletePositionUserMap);

						Long positionUserId = MapUtils.getLong(positionUserMap, "ID");
						// 删除PositionUserServiceStation表数据
						crmServiceDao.deletePositionUserServiceStation(channelCompany.getId(), positionUserId,
								currentTime);
					} else {
						// 新增/修改逻辑
						Long positionUserId = null;
						// 没有存在的用户职位信息
						if (MapUtils.isEmpty(positionUserMap)) {
							Map<String, Object> savePositionUserMap = new HashMap<>();
							savePositionUserMap.put("PositionID", positionId);
							savePositionUserMap.put("UserPhone", phone);
							UserT userT = userTDao.getUserByPhone(phone);
							if (null != userT) {
								savePositionUserMap.put("UserID", userT.getId());
							}
							savePositionUserMap.put("Creator", companyId);
							savePositionUserMap.put("CreateTime", LocalTimeUtil.getRealCurrentTime());
							crmServiceDao.savePositionContactToTable(savePositionUserMap);
							positionUserId = MapUtils.getLong(savePositionUserMap, "positionUserID");
						} else {
							positionUserId = MapUtils.getLong(positionUserMap, "ID");

							// 如果存在用户职位信息，则删除现有管辖信息
							crmServiceDao.deletePositionUserServiceStation(channelCompany.getId(), positionUserId,
									currentTime);
						}

						// 遍历保存新管辖信息
						List<String> stationList = (List<String>) MapUtils.getObject(crmPositionMap, "stations");
						if (CollectionUtils.isNotEmpty(stationList)) {
							for (String stationNo : stationList) {
								Long stationId = null;
								if (serviceStationIdMap.containsKey(stationNo)) {
									stationId = MapUtils.getLong(serviceStationIdMap, stationNo);
								} else {
									Map<String, Object> queryMap = new HashMap<>(2);
									queryMap.put("stationNo", stationNo);
									queryMap.put("companyId", channelCompany.getId());
									// 查询是否存在授权，无授权跳出
									List<Map<String, Object>> ssRepairMap = ssRepairTDao
											.getSSRepairTByServiceStationNoCompanyID(queryMap);
									if (CollectionUtils.isNotEmpty(ssRepairMap)) {
										stationId = MapUtils.getLong(ssRepairMap.get(0), "ServiceStationID");
										serviceStationIdMap.put(stationNo, stationId);
									} else {
										continue;
									}
								}
								// 保存管辖信息
								Map<String, Object> savePositionUserServiceStationMap = new HashMap<>();
								savePositionUserServiceStationMap.put("ServiceStationID", stationId);
								savePositionUserServiceStationMap.put("ServiceStationNo", stationNo);
								savePositionUserServiceStationMap.put("CompanyID", companyId);
								savePositionUserServiceStationMap.put("PositionUserID", positionUserId);
								savePositionUserServiceStationMap.put("Creator", companyId);
								savePositionUserServiceStationMap.put("CreateTime", LocalTimeUtil.getRealCurrentTime());
								crmServiceDao.savePositionUserServiceStationToTable(savePositionUserServiceStationMap);
							}
						}
					}
				}
			} catch (Exception e) {
				TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
				LOG.error(e.getMessage(), e);
				ParameterTool.writeErrorResponse(response);
			}
			ParameterTool.writeResponse(response, 0, "区域管辖信息同步成功");
		}
		return null;
	}

	/**
	 * dbu 同步管辖关系
	 *
	 * @param map
	 * @return
	 */
	@Override
	public ModelAndView syncPositionInfoDub(Map<String, Object> map) {
//		lock.lock();
//		//创建一个事务配置对象
//		DefaultTransactionDefinition dt = new DefaultTransactionDefinition();
//		//根据需求，选择不同的事务传播行为
//		//例如：嵌套事务 PROPAGATION_REQUIRES_NEW 每次开启一个新的事务
//		dt.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW);
//		//获取事务状态
//		TransactionStatus transactionStatus = platformTransactionManager.getTransaction(dt);
		HttpServletResponse response = (HttpServletResponse) map.get("response");
		try {
			// sprint52 需求
			// 1.解决并发重复数据问题 （完成），
			//2.优化同步数据慢得问题，
			//3.加上事务管理，完成
			//4.梳理接口逻辑优化，
			//5.添加必填数据校验，
			//6.报错信息精确
			//验证参数  phone  stationNo为空  stationNo 是否在SSRepair_T 表中
			//3.4.0需求: 由于dbu派工表变更，之前逻辑全部变更为新的
			String companyStr = map.get("company").toString();
			List<Map<String, Object>> crmPositionInfoList = JSONArray
					.fromObject(map.get(CRMServiceConst.CRM_REQUEST_PARAMS).toString());
			CompanyT company = companyTDao.getCompanyInfoByCompanyNo(companyStr);
			// 获取企业id
			long companyId = company.getId();
			String msg = this.validationParameters(crmPositionInfoList, companyStr, companyId);
			//将错误信息返回
			if (StringUtils.isNotBlank(msg)) {
				ParameterTool.writeErrorResponse(response, -1, msg);
				return null;
			}
			//操作position表
			this.updateAndSavePosition(crmPositionInfoList, companyId);
			//操作PositionUser 表
			this.updateAndSavePositionUser(crmPositionInfoList, companyId);
			//操作PositionUserServiceStation 表
			this.updateAndSavePositionUserServiceStation(crmPositionInfoList, companyId);
			//提交事务
//			platformTransactionManager.commit(transactionStatus);
//			lock.unlock();
		} catch (Exception e) {
			e.printStackTrace();
			LOG.error(e);
			//回滚事务
//			platformTransactionManager.rollback(transactionStatus);
//			lock.unlock();
			ParameterTool.writeResponse(response, -1, "系统未知错误");
			return null;
		}
		ParameterTool.writeResponse(response, 0, "区域管辖信息同步成功");
		return null;
	}

	/**
	 * PositionUserServiceStation 集合 批量  添加 更新和删除
	 *
	 * @param crmPositionInfoList
	 * @param companyId
	 */
	private void updateAndSavePositionUserServiceStation(List<Map<String, Object>> crmPositionInfoList, Long companyId) {
//		LOG.error("--+PositionUserServiceStation+++--- 开始为" + LocalTimeUtil.getRealCurrentTime());
		LOG.error("--+PositionUserServiceStation+++--- 开始为" + System.currentTimeMillis());
		//查询 positionuser
		List<String> crmIdList = crmPositionInfoList.stream().map(e -> {
			String crmId = MapUtils.getString(e, "crmId");
			return crmId;
		}).collect(Collectors.toList());
		List<SSRepairT> ssRepairBusinessNoByCompanyIDList = serviceStationDao.getSSRepairBusinessNoByCompanyID(companyId);
		List<PositionUserT> listbyCrm = positionUserTDao.getListbyCrm(crmIdList);

		List<Map<String, Object>> stations = crmPositionInfoList.stream().filter(e -> {
			return null != (List<Map<String, Object>>) e.get("stations")
					&& ((List<Map<String, Object>>) e.get("stations")).size() > 0;
		}).collect(Collectors.toList());
		if (CollectionUtils.isEmpty(stations)) {
			LOG.error("------------stations 为空");
			return;
		}
		List<Map<String, Object>> stationAndPositionUserList = new ArrayList<>();
		//拼装参数   将PositionUserID  拼装到stations 中
		for (Map<String, Object> map : crmPositionInfoList) {
			String crmId = MapUtils.getString(map, "crmId");
			List<PositionUserT> positionUserTList = listbyCrm.stream().filter(h -> h.getCrmId().equals(crmId)).collect(Collectors.toList());
			PositionUserT positionUserT = positionUserTList.get(positionUserTList.size() - 1);
			List<Map<String, Object>> stationList = (List<Map<String, Object>>) map.get("stations");
			if (CollectionUtils.isNotEmpty(stationList)) {
				for (Map<String, Object> objectMap : stationList) {
					objectMap.put("PositionUserID", positionUserT.getID());
				}
			}
			stationAndPositionUserList.addAll(stationList);
		}
		// 查询所有的    positionUserServiceStation
		int pageSize = 1000;
		int total = stationAndPositionUserList.size();
		int pageSum = (total + pageSize - 1) / pageSize;
		List<Map<String, Object>> positionUserServiceStationListParam = new ArrayList<>();
		for (int i = 0; i < pageSum; i++) {
			List<Map<String, Object>> collect = stationAndPositionUserList.stream().skip(i * pageSize)
					.limit(pageSize).collect(Collectors.toList());
			List<Map<String, Object>> positionUserServiceStationParamByPage = crmServiceDao.getPositionUserServiceStationInfoByServiceStationNoAndCompanyIDANDPositionIDList(collect, companyId);
			if (CollectionUtils.isNotEmpty(positionUserServiceStationParamByPage)) {
				positionUserServiceStationListParam.addAll(positionUserServiceStationParamByPage);
			}
		}
		//positionuserServiceStaion_操作的集合；
		List<Map<String, Object>> addPositionuserServiceStaionList = new ArrayList<>();
		List<Map<String, Object>> deletePositionuserServiceStaionList = new ArrayList<>();
		// 将添加的集合，删除的集合分类
		for (int i = 0; i < crmPositionInfoList.size(); i++) {
			// 获取岗位信息
			Map<String, Object> crmPositionMap = crmPositionInfoList.get(i);
			//获取服务站List
			List<Map<String, Object>> crmPositionStationsMap = (List<Map<String, Object>>) crmPositionMap
					.get("stations");
			if (CollectionUtils.isEmpty(crmPositionStationsMap)) {
				continue;
			}
			String crmId = MapUtils.getString(crmPositionMap, "crmId");
			//获取 positionUserT 的相关信息
			List<PositionUserT> positionUserTList = listbyCrm.stream().filter(e -> e.getCrmId().equals(crmId)).collect(Collectors.toList());
			PositionUserT positionUserT = positionUserTList.get(positionUserTList.size() - 1);
			//循环遍历  服务站List
			for (int k = 0; k < crmPositionStationsMap.size(); k++) {
				Map<String, Object> crmPositionStationMap = (Map<String, Object>) crmPositionStationsMap.get(k);
				String requstStatus = crmPositionStationMap.get("requstStatus").toString();
				String stationNo = MapUtils.getString(crmPositionStationMap, "stationNo");

				List<SSRepairT> ssRepairTList = ssRepairBusinessNoByCompanyIDList.stream().filter(e -> e.getBusinessno().equals(stationNo)).collect(Collectors.toList());
				SSRepairT ssRepairT = ssRepairTList.get(ssRepairTList.size() - 1);
				//拼装参数-----PositionuserServiceStaion  的参数
				Map<String, Object> userServiceMap = CRMRequestMapToAppMapUtils
						.toPositionUserServiceMap(ssRepairT, positionUserT.getID(),
								requstStatus, companyId);
				// 验证 stationNo 是否存在
				boolean positionUserServiceStationnNullFlag = CollectionUtils.isEmpty(positionUserServiceStationListParam);
				boolean positionUserServiceStationnFlag = false;
				if (!positionUserServiceStationnNullFlag) {
					positionUserServiceStationnFlag = positionUserServiceStationListParam.stream().anyMatch(e -> {
						String stationNoParam = MapUtils.getString(e, "ServiceStationNo");
						String PositionUserID = MapUtils.getString(e, "PositionUserID");
						return stationNoParam.equals(stationNo) && PositionUserID.equals("" + positionUserT.getID());
					});
				}

				if (userServiceMap.get("Status").toString().equals("1")) {// 新增
					if (positionUserServiceStationnNullFlag || !positionUserServiceStationnFlag) {
						//放入到添加的集合
						addPositionuserServiceStaionList.add(userServiceMap);
					}
				} else if (userServiceMap.get("Status").toString().equals("2")) {// 删除
					if (positionUserServiceStationnFlag) {
						//放入到删除的集合
						List<Map<String, Object>> collect = positionUserServiceStationListParam.stream().filter(e -> {
							String stationNoParam = MapUtils.getString(e, "ServiceStationNo");
							String PositionUserID = MapUtils.getString(e, "PositionUserID");
							return stationNoParam.equals(stationNo) && PositionUserID.equals("" + positionUserT.getID());
						}).collect(Collectors.toList());
						Map<String, Object> map = collect.get(collect.size() - 1);
//						userServiceMap.put("id",map.get("ID"));
						//Deleter},DeleteTime=#{item.DeleteTime
						for (Map<String, Object> objectMap : collect) {
							objectMap.put("Deleter", userServiceMap.get("Deleter"));
							objectMap.put("DeleteTime", userServiceMap.get("DeleteTime"));
						}
						deletePositionuserServiceStaionList.addAll(collect);
					}
				}
			}
		}
//		LOG.error("--+PositionUserServiceStation+++--- 结束为" + LocalTimeUtil.getRealCurrentTime());
		LOG.error("--+PositionUserServiceStation+++--- 结束为" + System.currentTimeMillis());
		//  根据分页批量  添加 更新 删除
		ArrayList<Map<String, Object>> disaddPositionuserServiceStaionList = addPositionuserServiceStaionList.stream().collect(Collectors.collectingAndThen(
				Collectors.toCollection(() -> new TreeSet<>(Comparator.comparing(p -> ((Long) p.get("PositionUserID")) + ((String) p.get("ServiceStationNo"))))),
				ArrayList::new));
		this.saveOrUpdatePageList(disaddPositionuserServiceStaionList, 100, 7);
		this.saveOrUpdatePageList(deletePositionuserServiceStaionList, 100, 8);
	}

	/**
	 * PositionUser 集合 批量  添加 更新和删除
	 *
	 * @param crmPositionInfoList
	 * @param companyId
	 */
	public  void updateAndSavePositionUser(List<Map<String, Object>> crmPositionInfoList, Long companyId) {
//		LOG.error("--+PositionUser+++--- 开始为" + LocalTimeUtil.getRealCurrentTime());
		LOG.error("--+PositionUser+++--- 开始为" + System.currentTimeMillis());
		//查询 position
		List<PositionT> positionTAll = positionTMapper.getAll();
		//查询 positionuser
		List<String> crmIdList = crmPositionInfoList.stream().map(e -> {
			String crmId = MapUtils.getString(e, "crmId");
			return crmId;
		}).collect(Collectors.toList());
		// 查询全部的  crm  集合
		List<PositionUserT> positionUserTlistbyCrm = positionUserTDao.getListbyCrm(crmIdList);
		//positionUser_操作的集合；
		List<Map<String, Object>> addpositionUserList = new ArrayList<>();
		List<Map<String, Object>> updatepositionUserList = new ArrayList<>();
		List<Map<String, Object>> deletepositionUserList = new ArrayList<>();
		// 循环职位信息
		for (int i = 0; i < crmPositionInfoList.size(); i++) {
			// 获取岗位信息
			Map<String, Object> crmPositionMap = crmPositionInfoList.get(i);
			// 获取企业信息
			crmPositionMap.put("CompanyID", companyId);
			// 转化成app postion table需要的字段参数
			Map<String, Object> appPositionMap = CRMRequestMapToAppMapUtils.toDBUPositionInfoMap(crmPositionMap);
			if (appPositionMap == null)
				continue;
			boolean empty = CollectionUtils.isEmpty(positionTAll);
			List<PositionT> collect = null;
			String crmPostNoParam = MapUtils.getString(appPositionMap, "CrmPostNo");
			Long creatorParam = MapUtils.getLongValue(appPositionMap, "Creator");
			Integer levelParam = MapUtils.getInteger(appPositionMap, "Level");
			if (CollectionUtils.isNotEmpty(positionTAll)) {
				collect = positionTAll.stream().filter(e -> {
					String crmPostNo = e.getCrmPostNo();
					Integer level = e.getLevel();
					Long creator = e.getCreator();
					return crmPostNo.equals(crmPostNoParam) && creator.equals(creatorParam) && level.equals(levelParam);
				}).collect(Collectors.toList());
			}
			PositionT positionT = collect.get(collect.size() - 1);
			// 2、区域工程师信息
			crmPositionMap.put("positionId", positionT.getID());
			Map<String, Object> appPositionContactMap = CRMRequestMapToAppMapUtils
					.toPositionContactInfo(crmPositionMap);
			// 联系人列表为空
			if (appPositionContactMap == null || appPositionContactMap.size() == 0) {
				continue;
			}
			boolean positionUserFlag = CollectionUtils.isEmpty(positionUserTlistbyCrm);
			String crmId = MapUtils.getString(appPositionContactMap, "CrmId");
			List<PositionUserT> crmIdParam = positionUserTlistbyCrm.stream().filter(e -> {
				return e.getCrmId().equals(crmId);
			}).collect(Collectors.toList());
            Long positionUserId = null;
            if (CollectionUtils.isNotEmpty(crmIdParam)) {
                positionUserId = crmIdParam.get(crmIdParam.size() - 1).getID();
            }
			if (appPositionContactMap.get("Status").toString().equals("1")) {// 新增
				if (positionUserFlag || CollectionUtils.isEmpty(crmIdParam)) {
					addpositionUserList.add(appPositionContactMap);
				}

			} else if (appPositionContactMap.get("Status").toString().equals("3")) {// 修改
				if (positionUserFlag || CollectionUtils.isEmpty(crmIdParam)) {
					appPositionContactMap.put("CreateTime", LocalTimeUtil.getRealCurrentTime());
					addpositionUserList.add(appPositionContactMap);
				} else {
					updatepositionUserList.add(appPositionContactMap);
				}

			} else if (appPositionContactMap.get("Status").toString().equals("2")) {// 删除
				if (CollectionUtils.isNotEmpty(crmIdParam)) {// 既然是删除就不创建了
                    appPositionContactMap.put("positionUserId", positionUserId);
					deletepositionUserList.add(appPositionContactMap);
				}
			}
		}
//		LOG.error("--+PositionUser+++--- 结束为" + LocalTimeUtil.getRealCurrentTime());
		LOG.error("--+PositionUser+++--- 结束为" + System.currentTimeMillis());
		//addpositionUserList 去重
		ArrayList<Map<String, Object>> disaddpositionUserList = addpositionUserList.stream().collect(Collectors.collectingAndThen(
				Collectors.toCollection(() -> new TreeSet<>(Comparator.comparing(p -> (String) p.get("CrmId")))),
				ArrayList::new));
		this.saveOrUpdatePageList(disaddpositionUserList, 100, 4);
		this.saveOrUpdatePageList(updatepositionUserList,100, 5);
		this.saveOrUpdatePageList(deletepositionUserList, 100, 6);
	}

	/**
	 * Position 集合 批量  添加 更新和删除
	 * @param crmPositionInfoList
	 * @param companyId
	 */
	public void updateAndSavePosition(List<Map<String, Object>> crmPositionInfoList, Long companyId) {

//		LOG.error("--+Position+++--- 开始为" + LocalTimeUtil.getRealCurrentTime());
		LOG.error("--+Position+++--- 开始为" + System.currentTimeMillis());
		//查询 position
		List<PositionT> positionTAll = positionTMapper.getAll();
		//position 操作的集合；
		List<Map<String, Object>> addPositionList = new ArrayList<>();
		List<Map<String, Object>> updatePositionList = new ArrayList<>();
		List<Map<String, Object>> deletePositionList = new ArrayList<>();
		for (int i = 0; i < crmPositionInfoList.size(); i++) {
			// 获取岗位信息
			Map<String, Object> crmPositionMap = crmPositionInfoList.get(i);
			// 获取企业信息
			crmPositionMap.put("CompanyID", companyId);
			// 转化成app postion table需要的字段参数
			Map<String, Object> appPositionMap = CRMRequestMapToAppMapUtils.toDBUPositionInfoMap(crmPositionMap);
			if (appPositionMap == null)
				continue;

			//查询是否有相同的职位信息
			boolean empty = CollectionUtils.isEmpty(positionTAll);
			List<PositionT> collect = null;
			String crmPostNoParam = MapUtils.getString(appPositionMap, "CrmPostNo");
			Long creatorParam = MapUtils.getLongValue(appPositionMap, "Creator");
			Integer levelParam = MapUtils.getInteger(appPositionMap, "Level");
			if (CollectionUtils.isNotEmpty(positionTAll)) {
				collect = positionTAll.stream().filter(e -> {
					String crmPostNo = e.getCrmPostNo();
					Integer level = e.getLevel();
					Long creator = e.getCreator();
					return crmPostNo.equals(crmPostNoParam) && creator.equals(creatorParam) && level.equals(levelParam);
				}).collect(Collectors.toList());
			}

			if (appPositionMap.get("Status").toString().equals("1")) {// 新增
				if (empty || CollectionUtils.isEmpty(collect)) {
//					appPositionMap.put("positionIdStr", UUID.randomUUID().toString().replace("-", ""));
					addPositionList.add(appPositionMap);
				} else {
					PositionT positionT = collect.get(collect.size() - 1);
					appPositionMap.put("positionId", positionT.getID());
				}
			} else if (appPositionMap.get("Status").toString().equals("3")) {// 修改
				if (empty || CollectionUtils.isEmpty(collect)) {
					appPositionMap.put("Updator", companyId);
					appPositionMap.put("Creator", companyId);
					appPositionMap.put("CreateTime", LocalTimeUtil.getRealCurrentTime());
					addPositionList.add(appPositionMap);
				} else {
					updatePositionList.add(appPositionMap);
				}
			} else if (appPositionMap.get("Status").toString().equals("2")) {// 删除
                //已经和sf开发确认    不存在 删除区域的功能，只存在删除管辖关系  -----即  删除positionuser表
//				if (CollectionUtils.isNotEmpty(collect)) {
//					deletePositionList.add(appPositionMap);
//				}
			} else { // 新增
				LOG.info("请求类型传递不正确");
				continue;
			}
		}
//		LOG.error("--+Position+++--- 结束为" + LocalTimeUtil.getRealCurrentTime());
		LOG.error("--+Position+++--- 结束为" + System.currentTimeMillis());
		ArrayList<Map<String, Object>> disaddPositionList = addPositionList.stream().collect(Collectors.collectingAndThen(
				Collectors.toCollection(() -> new TreeSet<>(Comparator.comparing(p -> (String) p.get("CrmPostNo")))),
				ArrayList::new));
		this.saveOrUpdatePageList(disaddPositionList, 100, 1);
		this.saveOrUpdatePageList(updatePositionList,100,2);
		this.saveOrUpdatePageList(deletePositionList,100,3);

	}

	public void saveOrUpdatePageList(List<Map<String, Object>> list,int pageSize,int type) {
		int addtotal = list.size();
//		LOG.error("------------------type 值为" + type);

//		LOG.error("--++++++++++++--- 值为" + list.toString());
//		LOG.error("--++++++++++++--- 值为" + LocalTimeUtil.getRealCurrentTime());
		LOG.error("--++++++++++++saveOrUpdatePageList--- 值为" + System.currentTimeMillis());
		int pageSum = (addtotal + pageSize - 1) / pageSize;
		for (int i = 0; i < pageSum; i++) {
			List<Map<String, Object>> collect = list.stream().skip(i * pageSize).limit(pageSize).
					collect(Collectors.toList());
			if (type == 1) {//position 添加
				positionTMapper.insertList(collect);
			} else if (type == 2) { //position 更新
				positionTMapper.updateList(collect);
			} else if (type == 3) {//positionuser PositionUserServiceStation  删除
				crmServiceDao.deletePositionUserList(collect);//删除职位与人员关联表关系
				crmServiceDao.deletePositionUserServiceStationByPositionUserList(collect);
			}else if (type == 4){  //positionuser 添加
				crmServiceDao.savePositionUserList(collect);
            }else if (type == 5){   //positionuser 更新
				crmServiceDao.updatePositionContactToTableDbuList(collect);
			} else if (type == 6) { //positionuser 删除
				crmServiceDao.deletePositionUserList(collect);//删除职位与人员关联表关系
				crmServiceDao.deletePositionUserServiceStationByPositionUserList(collect);
			} else if (type == 7) {//PositionUserServiceStation 添加
				crmServiceDao.savePositionUserServiceStationList(collect);
			} else if (type == 8) {//PositionUserServiceStation 删除
				crmServiceDao.deletePositionUserServiceStationByIdList(collect);
			}
		}
//		LOG.error("---------------- 值为" + LocalTimeUtil.getRealCurrentTime());
		LOG.error("----------------saveOrUpdatePageList 值为" + System.currentTimeMillis());
	}

	/**
	 * DBU  验证参数是否正确     phone  stationNo domain stationNo 是否在SSRepair_T 表中
	 *
	 * @param crmPositionInfoList
	 * @return
	 */
	private String validationParameters(List<Map<String, Object>> crmPositionInfoList, String companyStr, Long companyId) {
		if (CollectionUtils.isEmpty(crmPositionInfoList)) {
			return "参数为空";
		}
		//验证domain
		boolean domainIdflag = crmPositionInfoList.stream().anyMatch(e -> {
			String domainId = MapUtils.getString(e, "domainId");
			String domainName = MapUtils.getString(e, "domainName");
			if (StringUtils.isBlank(domainId)) {
				LOG.error(domainName + "的domainId为空");
			}
			return StringUtils.isBlank(domainId);
		});
		if (domainIdflag) {
			return "domainId为空";
		}

		//		crmid为空
		for (Map<String, Object> map : crmPositionInfoList) {
			String crmId = MapUtils.getString(map, "crmId");
			String domainName = MapUtils.getString(map, "domainName");
			if (StringUtils.isBlank(crmId)) {
				LOG.error(domainName + "的crmid为空");
//				this.saveException(map.toString(), "服务站人员电话号码为空", companyStr);
				return domainName + "的crmid为空";
			}
		}
		//验证phone
		for (Map<String, Object> map : crmPositionInfoList) {
			String phone = MapUtils.getString(map, "phone");
			String domainName = MapUtils.getString(map, "domainName");
			if (StringUtils.isBlank(phone)) {
				LOG.error(domainName + "的phone为空");
				this.saveException(map.toString(), "服务站人员电话号码为空", companyStr);
				return "phone为空";
			}
		}
		//验证 stationNo
		List<Map<String, Object>> crmPositionInfoListByStations = crmPositionInfoList.stream().filter(e -> {
			List<Map<String, Object>> crmPositionStationsMap = (List<Map<String, Object>>) e
					.get("stations");
			return crmPositionStationsMap != null && crmPositionStationsMap.size() > 0;
		}).collect(Collectors.toList());
		if (CollectionUtils.isNotEmpty(crmPositionInfoListByStations)) {
			boolean stationNoFlag = crmPositionInfoListByStations.stream().anyMatch(e -> {
				List<Map<String, Object>> crmPositionStationsMap = (List<Map<String, Object>>) e
						.get("stations");
				return crmPositionStationsMap.stream().anyMatch(station -> {
					Map<String, Object> crmPositionStationMap = (Map<String, Object>) station;
					return StringUtils.isEmpty(MapUtils.getString(crmPositionStationMap, "stationNo"));
				});
			});
			if (stationNoFlag) {
				return "stationNo为空";
			}
			List<Map<String, Object>> stations = new ArrayList<>();
			//验证服务站在SSRepair_T
			for (Map<String, Object> crmPositionInfoListByStation : crmPositionInfoListByStations) {
				List<Map<String, Object>> mapList = (List<Map<String, Object>>) crmPositionInfoListByStation.get("stations");
				stations.addAll(mapList);
			}
			if (CollectionUtils.isNotEmpty(stations)) {
				List<String> stationNo = stations.stream().map(e -> (String) e.get("stationNo")).collect(Collectors.toList());
				List<SSRepairT> ssRepairBusinessNoByCompanyIDList = serviceStationDao.getSSRepairBusinessNoByCompanyID(companyId);
				List<String> ssRepairBusinessNoByCompanyID = ssRepairBusinessNoByCompanyIDList.stream().map(e -> e.getBusinessno()).collect(Collectors.toList());
				List<String> collect = stationNo.stream().filter(e -> !ssRepairBusinessNoByCompanyID.contains(e)).collect(Collectors.toList());
				if (CollectionUtils.isNotEmpty(collect)) {
					this.saveException(collect.toString(), "服务站编号：" + collect.toString() + "，服务站数据未同步到APP系统", companyStr);
					return "服务站编号：" + collect.toString() + "，服务站数据未同步到APP系统";
				}
			}
		}

		//将手机号不在user_t 表中的数据记录
		List<String> phoneList = crmPositionInfoList.stream().map(e -> MapUtils.getString(e, "phone")).collect(Collectors.toList());
		if (CollectionUtils.isNotEmpty(phoneList)) {
			//查询 user_t表
			List<String> phoneByPhoneList = userTDao.getPhoneByPhoneList(phoneList);
			List<String> collect = phoneList.stream().filter(e -> !phoneByPhoneList.contains(e)).collect(Collectors.toList());
			this.saveException(collect.toString(), "人员账户在APP系统未创建，电话号码:" + collect.toString(), companyStr);
		}
		return null;
	}

	/**
	 * 记录同步有问题的数据
	 *
	 * @param data
	 * @param exceptionInfo
	 * @param companyStr
	 */
	public void saveException(String data, String exceptionInfo, String companyStr) {
		APIExceptionT crmApiException = new APIExceptionT();
		crmApiException.setAPIName("synPositionInfo");
		crmApiException.setCompanyNo(companyStr);
		crmApiException.setData(data);
		crmApiException.setDirection(0);
		crmApiException.setExceptionInfo(exceptionInfo);
		crmApiException.setFlag(0);
		crmApiException.setSystemTime(LocalTimeUtil.getRealCurrentTime());
		crmServiceDao.saveExceptionToExpTable(crmApiException);
	}

	@Transactional
	@Override
	public ModelAndView syncExceptionsToApp(Map<String, Object> httpMap) {
		HttpServletRequest request = (HttpServletRequest) httpMap.get("request");
		HttpServletResponse response = (HttpServletResponse) httpMap.get("response");
		JSONArray crmExceptions = JSONArray.fromObject(httpMap.get(CRMServiceConst.CRM_REQUEST_PARAMS).toString());
		String company = httpMap.get("company").toString();
		if (crmExceptions != null && crmExceptions.size() > 0) {
			for (int i = 0; i < crmExceptions.size(); i++) {
				Map<String, Object> crmExceptionMap = this.toHashMap(crmExceptions.getJSONObject(i));
				if (!crmExceptionMap.containsKey("company")) {
					crmExceptionMap.put("company", company);
				}
				Map<String, Object> appExceptionMap = this.turnCRMParamDataToAppTableData(crmExceptionMap);
				try {
					crmServiceDao.saveExceptionToTable(appExceptionMap);
				} catch (Exception e) {
					LOG.info(appExceptionMap);
					LOG.info(e.getMessage());
				}

			}
		}
		JSONObject jsonData = new JSONObject();
		JSONObject jsonObject = new JSONObject();
		jsonObject.put("status", 0);
		jsonObject.put("msg", "保存异常信息成功");
		jsonObject.put("data", jsonData);
		ParameterTool.writeResponse(response, jsonObject.toString());
		return null;
	}

	@Override
	public void syncServiceStationLonAndLat(Map<String, Object> map) {
		// TODO Auto-generated method stub
		if (map != null && map.containsKey("serviceStationId") && map.containsKey("lat") && map.containsKey("lon")) {
			List<SSRepairT> repairList = serviceStationDao.getSSRepairListByServiceStaionId(map);

			if (repairList != null && repairList.size() > 0) {
				for (SSRepairT repairT : repairList) {
					CompanyT company = companyTDao.getCompanyInfoByCompanyID(repairT.getCompanyid());

					List<Map<String, Object>> lonAndLatList = new ArrayList<Map<String, Object>>();
					Map<String, Object> lonAndLat = new HashedMap<String, Object>();
					lonAndLat.put("stationNo", repairT.getBusinessno());
					if (company.getCompanyNo().equals("CCI") || company.getCompanyNo().equals("XCEC")) {
						lonAndLat.put("positionLon", map.get("lon"));
						lonAndLat.put("positionLat", map.get("lat"));
					} else {
						lonAndLat.put("positionLon", map.get("lat"));
						lonAndLat.put("positionLat", map.get("lon"));
					}
					lonAndLat.put("address", map.get("address"));
					lonAndLat.put("provice", map.get("province"));
					lonAndLat.put("city", map.get("city"));
					lonAndLat.put("area", map.get("area"));
					lonAndLat.put("hotLineOne", MapUtils.getString(map, "hotLineOne", ""));
					lonAndLat.put("hotLineTwo", MapUtils.getString(map, "hotLineTwo", ""));
					lonAndLat.put("detailedAddress", MapUtils.getString(map, "detailedAddress", ""));
					lonAndLatList.add(lonAndLat);

					try {
						CRMApiUtils.getCRMServiceApi().updateServiceStationLonAndLatInfos(company.getCompanyNo(),
								lonAndLatList);
					} catch (Exception ex) {
						LOG.error("服务站经纬度信息同步至CRM失败：" + ex.getMessage(), ex);
					}

				}
			}

		}
	}

	/**
	 * 从redis中获取异常工单信息，如果存在则调取接口
	 */
	@Override
	public void syncExceptionalOrderInfoToCRM(boolean isSync) {
		// 1、工单信息异常数据
		List<WorkOrderSynchroT> infoList = workOrderSynchroService.selectByInfo(null);
		// 2、工单状态异常数据-DBU
		List<WorkOrderSynchroT> statusDBUList = workOrderSynchroService.selectByStatus("CCI");
		// 2、工单状态异常数据-DCEC
		List<String> statusDCECList = workOrderSynchroService.selectGroupOrderNoByStatus("DCEC");
		// 2、工单状态异常数据-XCEC
		List<String> statusXCECList = workOrderSynchroService.selectGroupOrderNoByStatus("XCEC");
		// 3、工单用户评价异常数据
		List<Map<String, Object>> exceptionalOrderAppraise = redisClientUtils
				.getObjectList(CRMServiceConst.KEY_ORDERAPPRAISE_EXCEPTIONAL_APP);
		// 4、DBU自主诊断
		List<Map<String, Object>> exceptionalActiveDiagnostics = redisClientUtils
				.getObjectList(CRMServiceConst.KEY_ORDERACTIVE_DIAGNOSTICS_EXCEPTIONAL_APP);
		// 5、DBU诊断维修结论
		List<Map<String, Object>> exceptionalDrConclusion = redisClientUtils
				.getObjectList(CRMServiceConst.KEY_DR_CONCLUSION_EXCEPTIONAL_APP);
		// 获取到工单异常信息
		if (CollectionUtils.isNotEmpty(infoList)) {
			for (WorkOrderSynchroT synchroInfo : infoList) {
				LOG.info("定时重传工单信息: " + synchroInfo);
				WorkOrderT workOrderT = workOrderTDao.selectWorkOrderByOrderNo(synchroInfo.getOrderNo());
				if(null != workOrderT && StringUtils.isNotBlank(workOrderT.getOrderNoCrm())){
					synchroInfo.setSyncStatus(1);
					synchroInfo.setOrderNoCrm(workOrderT.getOrderNoCrm());
					synchroInfo.setFailReason("工单同步成功；" + synchroInfo.getFailReason());
					workOrderSynchroService.updateById(synchroInfo);
					continue;
				}
				long minutes = LocalTimeUtil.getDurationMinutes(synchroInfo.getCreateTime());
				if (minutes > 60 * 24 * 60) {// 超时删除
					synchroInfo.setSyncStatus(1);
					synchroInfo.setFailReason("超过60天修改为同步成功；" + synchroInfo.getFailReason());
					workOrderSynchroService.updateById(synchroInfo);
					continue;
				}

				String channelName =synchroInfo.getChannelName();
				Map<String, Object> params = JSON.parseObject(synchroInfo.getOrderInfo());
				CRMResponeEntity entity = CRMApiUtils.getCRMServiceApi().syncAppOrderInfoToCRM(channelName,
						crmServiceDao, null, params,synchroInfo.getId());
				LOG.info("定时重传信息工单编号" + synchroInfo.getOrderNo() + "信息结果:" + entity);
			}
		}
		if (CollectionUtils.isNotEmpty(statusDBUList)) {
			for (WorkOrderSynchroT synchroInfo : statusDBUList) {
				LOG.info("DBU定时重传工单状态: " + synchroInfo);
				List<WorkOrderSynchroT> statusList = workOrderSynchroService.selectByOrderNo(synchroInfo.getOrderNo());
				if (CollectionUtils.isNotEmpty(statusList)) {
					WorkOrderSynchroT synchroMaxInfo = statusList.get(statusList.size() - 1);
					if(synchroMaxInfo.getSyncStatus() == 1 && synchroMaxInfo.getId() > synchroInfo.getId()){
						synchroInfo.setSyncStatus(1);
						synchroInfo.setFailReason("最新状态同步成功修改为同步成功；" + synchroInfo.getFailReason());
						workOrderSynchroService.updateById(synchroInfo);
						continue;
					}
				}
				long minutes = LocalTimeUtil.getDurationMinutes(synchroInfo.getCreateTime());
				if (minutes > 60 * 24 * 60) {// 超时删除
					synchroInfo.setSyncStatus(1);
					synchroInfo.setFailReason("超过60天修改为同步成功；" + synchroInfo.getFailReason());
					workOrderSynchroService.updateById(synchroInfo);
					continue;
				}
				String channelName =synchroInfo.getChannelName();
				Map<String, Object> params = JSON.parseObject(synchroInfo.getOrderInfo());
				CRMResponeEntity entity = CRMApiUtils.getCRMServiceApi().syncOrderStatusToCrm(channelName,
						crmServiceDao, null, params,synchroInfo.getId());
				LOG.info("DBU定时重传工单编号:" + synchroInfo.getOrderNo() + ",状态结果:" + entity);
			}
		}

		if (CollectionUtils.isNotEmpty(statusDCECList) && isSync) {
			for (String orderNo : statusDCECList) {
				List<WorkOrderSynchroT> statusList = workOrderSynchroService.selectByOrderNo(orderNo);
				Map<String, Object> params = new HashMap<>();
				if (CollectionUtils.isNotEmpty(statusList)) {
					WorkOrderSynchroT synchroInfo = statusList.get(statusList.size() -1);
                    List<ListStatusEntity> listStatusList = new ArrayList<>();
					for (WorkOrderSynchroT info : statusList) {
						ListStatusEntity status = new ListStatusEntity();
						status.setBillStatus(String.valueOf(info.getProcessStatus()));
						status.setOperationTime(info.getCreateTime());
						listStatusList.add(status);
						Map<String, Object> paramsStatus = JSON.parseObject(info.getOrderInfo());
						params.putAll(paramsStatus);
					}
					//出发地址
					String startLocation = "";
					Map<String,Object> chufaFlow = workOrderFlowTDao.getWorkOrderFlowByOrderIdAndStatus(synchroInfo.getOrderId(),10);
					if(MapUtils.isNotEmpty(chufaFlow) && chufaFlow.containsKey("Location")){
						startLocation = MapUtils.getString(chufaFlow,"Location","");
					}
					//到达地址
					String stopLocation = "";
					Map<String,Object> daodaFlow = workOrderFlowTDao.getWorkOrderFlowByOrderIdAndStatus(synchroInfo.getOrderId(),11);
					if(MapUtils.isNotEmpty(daodaFlow) && daodaFlow.containsKey("Location")){
						stopLocation = MapUtils.getString(daodaFlow,"Location","");
					}
					LOG.info("DCEC定时重传工单状态: " + synchroInfo);
					long minutes = LocalTimeUtil.getDurationMinutes(synchroInfo.getCreateTime());
					if (minutes > 60 * 24 * 60) {// 超时删除
						for (WorkOrderSynchroT info : statusList) {
							info.setSyncStatus(1);
							info.setFailReason("超过60天修改为同步成功；" + synchroInfo.getFailReason());
							workOrderSynchroService.updateById(info);
						}
						continue;
					}
					String channelName =synchroInfo.getChannelName();

					params.put("listStatus",listStatusList);
					params.put("startLocation",startLocation);
					params.put("stopLocation",stopLocation);
					LOG.info("DCEC定时重传开始工单编号:" + synchroInfo.getOrderNo() + ",参数:" + params);
					CRMResponeEntity entity = CRMApiUtils.getCRMServiceApi().syncOrderStatusToCrm(channelName,
							crmServiceDao, null, params,synchroInfo.getId());
					LOG.info("DCEC定时重传结束工单编号:" + synchroInfo.getOrderNo() + ",状态结果:" + entity);
					for (WorkOrderSynchroT info : statusList) {
						info.setSynchroCount(info.getSynchroCount() + 1);
						if (entity.getStatus() == CRMServiceConst.CRM_SYNC_CODE_SUCCESS) {
							info.setSyncStatus(1);
						} else {
							info.setSyncStatus(0);
							info.setFailReason(entity.toString());
						}
						workOrderSynchroService.updateById(info);
					}
				}
			}
		}

		if (CollectionUtils.isNotEmpty(statusDCECList) && !isSync) {
			for (String orderNo : statusDCECList) {
				List<WorkOrderSynchroT> statusList = workOrderSynchroService.selectByOrderNo(orderNo);
				if (CollectionUtils.isNotEmpty(statusList)) {
					for (WorkOrderSynchroT synchroInfo : statusList) {
						if(synchroInfo.getSyncStatus() == 0){
							LOG.info("DCEC定时重传工单状态: " + synchroInfo);
							long minutes = LocalTimeUtil.getDurationMinutes(synchroInfo.getCreateTime());
							if (minutes > 60 * 24 * 60) {// 超时删除
								synchroInfo.setSyncStatus(1);
								synchroInfo.setFailReason("超过60天修改为同步成功；" + synchroInfo.getFailReason());
								workOrderSynchroService.updateById(synchroInfo);
								continue;
							}
							String channelName =synchroInfo.getChannelName();
							Map<String, Object> params = JSON.parseObject(synchroInfo.getOrderInfo());
							CRMResponeEntity entity = CRMApiUtils.getCRMServiceApi().syncOrderStatusToCrm(channelName,
									crmServiceDao, redisClientUtils, params,synchroInfo.getId());
							LOG.info("XCEC定时重传工单编号:" + synchroInfo.getOrderNo() + ",状态结果:" + entity);
							if (entity.getStatus() != CRMServiceConst.CRM_SYNC_CODE_SUCCESS) {
								break;
							}
						}
					}
				}
			}
		}

		if (CollectionUtils.isNotEmpty(statusXCECList)) {
			for (String orderNo : statusXCECList) {
				List<WorkOrderSynchroT> statusList = workOrderSynchroService.selectByOrderNo(orderNo);
				if (CollectionUtils.isNotEmpty(statusList)) {
					for (WorkOrderSynchroT synchroInfo : statusList) {
						if(synchroInfo.getSyncStatus() == 0){
							LOG.info("XCEC定时重传工单状态: " + synchroInfo);
							long minutes = LocalTimeUtil.getDurationMinutes(synchroInfo.getCreateTime());
							if (minutes > 60 * 24 * 60) {// 超时删除
								synchroInfo.setSyncStatus(1);
								synchroInfo.setFailReason("超过60天修改为同步成功；" + synchroInfo.getFailReason());
								workOrderSynchroService.updateById(synchroInfo);
								continue;
							}
							String channelName =synchroInfo.getChannelName();
							Map<String, Object> params = JSON.parseObject(synchroInfo.getOrderInfo());
							CRMResponeEntity entity = CRMApiUtils.getCRMServiceApi().syncOrderStatusToCrm(channelName,
									crmServiceDao, null, params,synchroInfo.getId());
							LOG.info("XCEC定时重传工单编号:" + synchroInfo.getOrderNo() + ",状态结果:" + entity);
							if (entity.getStatus() != CRMServiceConst.CRM_SYNC_CODE_SUCCESS) {
								break;
							}
						}
					}
				}
			}
		}
		if (exceptionalOrderAppraise != null && exceptionalOrderAppraise.size() > 0) {

			for (int i = 0; i < exceptionalOrderAppraise.size(); i++) {
				Map<String, Object> exceptionMap = exceptionalOrderAppraise.get(i);
				long minutes = LocalTimeUtil.getDurationMinutes(
						(String) exceptionMap.get(CRMServiceConst.CURRENTTIME_INTERFACE_EXCEPTIONAL_APP));
				if (minutes > 60 * 24 * 60) {// 超时删除
					redisClientUtils.listObjectRemove(CRMServiceConst.KEY_ORDERAPPRAISE_EXCEPTIONAL_APP, exceptionMap);
					continue;
				}
				Map<String, Object> cloneMap = (Map<String, Object>) BeanUtils.deepClone(exceptionMap);
				String channelName = (String) cloneMap.get(CRMServiceConst.CHANNEL_INTERFACE_EXCEPTIONAL_APP);
				Map<String, Object> params = (Map<String, Object>) cloneMap
						.get(CRMServiceConst.DATA_CRMPARAMS_EXCEPTIONAL_APP);
				CRMResponeEntity entity = CRMApiUtils.getCRMServiceApi().syncUserAppraisalInfoToCrm(channelName,
						crmServiceDao, null, params);
				if (entity.getStatus() != CRMServiceConst.CRM_SYNC_CODE_SUCCESS) {
					// 不处理
				} else {
					redisClientUtils.listObjectRemove(CRMServiceConst.KEY_ORDERAPPRAISE_EXCEPTIONAL_APP, exceptionMap);
				}
			}
		}
		if (exceptionalActiveDiagnostics != null && exceptionalActiveDiagnostics.size() > 0) {

			for (int i = 0; i < exceptionalActiveDiagnostics.size(); i++) {
				Map<String, Object> exceptionMap = exceptionalActiveDiagnostics.get(i);
				long minutes = LocalTimeUtil.getDurationMinutes(
						(String) exceptionMap.get(CRMServiceConst.CURRENTTIME_INTERFACE_EXCEPTIONAL_APP));
				if (minutes > 60 * 24 * 60) {// 超时删除
					redisClientUtils.listObjectRemove(CRMServiceConst.KEY_ORDERACTIVE_DIAGNOSTICS_EXCEPTIONAL_APP,
							exceptionMap);
					continue;
				}
				Map<String, Object> cloneMap = (Map<String, Object>) BeanUtils.deepClone(exceptionMap);
				String channelName = (String) cloneMap.get(CRMServiceConst.CHANNEL_INTERFACE_EXCEPTIONAL_APP);
				Map<String, Object> params = (Map<String, Object>) cloneMap
						.get(CRMServiceConst.DATA_CRMPARAMS_EXCEPTIONAL_APP);
				CRMResponeEntity entity = CRMApiUtils.getCRMServiceApi().activeDiagnostics(channelName, params, null);
				if (entity.getStatus() != CRMServiceConst.CRM_SYNC_CODE_SUCCESS) {
					// 不处理
				} else {
					redisClientUtils.listObjectRemove(CRMServiceConst.KEY_ORDERACTIVE_DIAGNOSTICS_EXCEPTIONAL_APP,
							exceptionMap);
				}
			}
		}
		if (exceptionalDrConclusion != null && exceptionalDrConclusion.size() > 0) {

			for (int i = 0; i < exceptionalDrConclusion.size(); i++) {
				Map<String, Object> exceptionMap = exceptionalDrConclusion.get(i);
				long minutes = LocalTimeUtil.getDurationMinutes(
						(String) exceptionMap.get(CRMServiceConst.CURRENTTIME_INTERFACE_EXCEPTIONAL_APP));
				if (minutes > 60 * 24 * 60) {// 超时删除
					redisClientUtils.listObjectRemove(CRMServiceConst.KEY_DR_CONCLUSION_EXCEPTIONAL_APP, exceptionMap);
					continue;
				}
				Map<String, Object> cloneMap = (Map<String, Object>) BeanUtils.deepClone(exceptionMap);
				String channelName = (String) cloneMap.get(CRMServiceConst.CHANNEL_INTERFACE_EXCEPTIONAL_APP);
				Map<String, Object> params = (Map<String, Object>) cloneMap
						.get(CRMServiceConst.DATA_CRMPARAMS_EXCEPTIONAL_APP);
				CRMResponeEntity entity = CRMApiUtils.getCRMServiceApi().drConclusion(channelName, params, null);
				if (entity.getStatus() != CRMServiceConst.CRM_SYNC_CODE_SUCCESS) {
					// 不处理
				} else {
					redisClientUtils.listObjectRemove(CRMServiceConst.KEY_DR_CONCLUSION_EXCEPTIONAL_APP, exceptionMap);
				}
			}
		}
	}

	/**
	 * CRM更新工单信息同步到APP系统
	 **/
	@Transactional
	@Override
	public ModelAndView updateCRMWorkOrderInfo(Map<String, Object> httpMap) {
		HttpServletRequest request = (HttpServletRequest) httpMap.get("request");
		HttpServletResponse response = (HttpServletResponse) httpMap.get("response");

		/**
		 * 1、将CRM请求参数转化成APP系统请求参数
		 */
		@SuppressWarnings("unchecked")
		Map<String, Object> requestMap = (Map<String, Object>) JSONObject
				.fromObject(httpMap.get(CRMServiceConst.CRM_REQUEST_PARAMS).toString());
		/**
		 * 2、定义返回结果
		 */
		JSONObject jsonObject = new JSONObject();
		Map<String, Object> orderMap = new HashMap<>();

		String appOrderNo = requestMap.get("orderNo").toString();
		String ESN = requestMap.get("esn").toString();
		String userPhone = requestMap.get("userPhone").toString();

		int workOrderCount = crmServiceDao.getWorkOrderInfoByOrderNo(appOrderNo);
		if (workOrderCount == 0) {
			// 返回给CRM系统错误信息（工单信息没有查询到）
			jsonObject.put("status", 1);
			jsonObject.put("msg", "工单信息未查询到");
			jsonObject.put("data", new JSONObject());
			ParameterTool.writeResponse(response, jsonObject.toString());
			return null;
		}
		orderMap.put("OrderNo", appOrderNo);
		/**
		 * 3、根据CompanyNo获取对应的Company信息
		 */
		CompanyT company = companyTDao.getCompanyInfoByCompanyNo(requestMap.get("company").toString());
		if (company == null) {
			LOG.info("服务渠道没有查询到");
			// 返回给CRM系统错误信息（服务站信息没有查询到）
			jsonObject.put("status", 1);
			jsonObject.put("msg", "服务渠道未查询到");
			jsonObject.put("data", new JSONObject());
			ParameterTool.writeResponse(response, jsonObject.toString());
			return null;
		}

		/**
		 * 4、根据ESN获取对应的EngineMsgId、OEMName 4.1先根据发动机号ESN从发动机信息表EngineMsg中查询是否有数据
		 */
		if (ESN != null && ESN.length() > 0) {
			orderMap.put("ESN", ESN);
			EngineMsg engineInfo = engineMsgDao.getEngineMsgByESN(orderMap);
			if (engineInfo != null) {
				orderMap.put("EngineMsgId", engineInfo.getId());
				orderMap.put("OEMName", engineInfo.getVehicleCompany());
			} else // 发动机信息表EngineMsg中没有查询到数据，就根据发动机号(ESN)和服务渠道serviceChannel调用CRM接口查询发动机数据
			{
				CRMResponeEntity crmResponeEntity = CRMApiUtils.getCRMServiceApi()
						.verifyEngineInfo(company.getCompanyNo(), orderMap.get("ESN").toString());
				if (crmResponeEntity.getStatus() == 0) {
					Map<String, Object> engineMsgMap = new HashedMap<String, Object>();
					engineMsgMap.put("ESN", orderMap.get("ESN"));
					engineMsgMap.put("SMN", crmResponeEntity.getData().get("SMN"));
					engineMsgMap.put("equipmentNo", crmResponeEntity.getData().get("equipmentNo"));
					engineMsgMap.put("vehicleCompany", crmResponeEntity.getData().get("vehicleCompany"));
					engineMsgMap.put("engineType", crmResponeEntity.getData().get("engineType"));
					engineMsgMap.put("manufactor", crmResponeEntity.getData().get("manufactor"));
					engineMsgMap.put("serviceChannel", crmResponeEntity.getData().get("serviceChannel"));
					engineMsgMap.put("saleDate", crmResponeEntity.getData().get("saleDate"));
					engineMsgDao.insertEngineMsg(engineMsgMap); // 保存
					// 将获取到的数据放到map中
					orderMap.put("EngineMsgId", engineMsgMap.get("id"));
					orderMap.put("OEMName", crmResponeEntity.getData().get("vehicleCompany").toString());
				}
			}
		}
		if (userPhone != null && userPhone.length() > 0) {
			List<UserT> users = loginDao.getUserByPhone(userPhone);
			if (users != null && users.size() > 0) {
				long lCustomerId = users.get(0).getId();
				orderMap.put("CustomerId", lCustomerId);
				orderMap.put("CustomerPhone", userPhone);
			}
		}
		/**
		 * 5、更新工单信息
		 **/
		int updateResult = crmServiceDao.updateWorkOrderInfoByOrderNoFromCRM(orderMap);
		if (updateResult > 0) {
			jsonObject.put("status", 0);
			jsonObject.put("msg", "工单信息更新成功");
			jsonObject.put("data", new JSONObject());
			ParameterTool.writeResponse(response, jsonObject.toString());
		} else {
			jsonObject.put("status", 1);
			jsonObject.put("msg", "工单信息更新失败");
			jsonObject.put("data", new JSONObject());
			ParameterTool.writeResponse(response, jsonObject.toString());
		}

		return null;
	}

	/**
	 * @return org.springframework.web.servlet.ModelAndView
	 * @Author Joe
	 * @Description //TODO 异常工单数据手动重传
	 * @Date 2:28 PM 2019/7/4
	 * @Param [map]
	 **/
	@Override
	public ModelAndView manualUpdateWorkOrderInfo(Map<String, Object> httpMap) {

		HttpServletRequest request = (HttpServletRequest) httpMap.get("request");
		HttpServletResponse response = (HttpServletResponse) httpMap.get("response");
		/**
		 * 1、将CRM请求参数转化成APP系统请求参数
		 */
		@SuppressWarnings("unchecked")
		Map<String, Object> requestMap = (Map<String, Object>) JSONObject
				.fromObject(httpMap.get(CRMServiceConst.CRM_REQUEST_PARAMS).toString());
		/**
		 * 2、定义返回结果
		 */
		JSONObject jsonObject = new JSONObject();

		if (requestMap != null && requestMap.containsKey("orderNo")) {
			String appOrderNo = requestMap.get("orderNo").toString();
			if (appOrderNo != null && appOrderNo.length() > 0) {
				// 1、主数据同步CRM异常
				Map<String, Object> workOrderMap = crmServiceDao
						.selectAllWorkOrderInfoNullOrderNoCrmByOrderNo(appOrderNo);
				if (workOrderMap != null) {
					String crmStationNo = "";
					Map<String, Object> ssRepairMap = new HashMap<>();
					ssRepairMap.put("serviceStationId", workOrderMap.get("ServiceStationId"));
					List<SSRepairT> ssRepairTS = serviceStationDao.getSSRepairListByServiceStaionId(ssRepairMap);
					if (ssRepairTS != null && ssRepairTS.size() > 0) {
						for (int j = 0; j < ssRepairTS.size(); j++) {
							SSRepairT ssRepairT = ssRepairTS.get(j);
							if (ssRepairT.getCompanyid().toString()
									.equals(workOrderMap.get("OrderChannel").toString())) {
								crmStationNo = ssRepairT.getBusinessno();
								break;
							}
						}
					}
					long companyId = MapUtils.getLongValue(workOrderMap, "OrderChannel", 0);
					CompanyT companyT = companyTDao.getCompanyInfoByCompanyID(companyId);
					UserT userT = loginDao.getUserByid(workOrderMap.get("Creator").toString());
					Map<String, Object> crmOrderMap = this.appWorkOrderToCrmWorkOrderData(workOrderMap, crmStationNo,
							companyT, userT);
					try {
						CRMResponeEntity crmResponeEntity = CRMApiUtils.getCRMServiceApi().syncAppOrderInfoToCRM(
								crmOrderMap.get("serviceChannel").toString(), crmServiceDao, redisClientUtils,
								crmOrderMap,null);
						if (crmResponeEntity.getStatus() != 0) {
							LOG.error("手动同步异常工单信息至CRM失败!状态:" + crmResponeEntity.getStatus() + ",错误信息:"
									+ crmResponeEntity.getMessage());
						} else {
							// 2 工单状态同步CRM异常
							if (workOrderMap.get("Comment") != null
									&& workOrderMap.get("Comment").toString().length() > 0) {
								List<Map<String, Object>> orderStatusList = crmServiceDao
										.getAllWorkOrderStatusByOrderId(MapUtils.getLong(workOrderMap, "ID"));
								if (orderStatusList != null && orderStatusList.size() > 0) {
									for (int j = 0; j < orderStatusList.size(); j++) {
										Map<String, Object> orderStatusFlow = orderStatusList.get(j);
										if (MapUtils.getIntValue(orderStatusFlow, "processStatus", 0) <= 2) {
											continue; // 1、工单已创建  2、待区域经理确认
										}
										Map<String, Object> crmOrderStatusMap = this
												.appWorkOrderStatusToCrmWorkOrderData(workOrderMap, orderStatusFlow,
														crmStationNo);
										LOG.error(JsonUtils.toJsonString(crmOrderStatusMap));
										CRMResponeEntity crmStatusResponeEntity = CRMApiUtils.getCRMServiceApi()
												.syncOrderStatusToCrm(crmOrderMap.get("serviceChannel").toString(),
														crmServiceDao, redisClientUtils, crmOrderStatusMap,null);
										if (crmStatusResponeEntity.getStatus() != 0) {
											LOG.error("手动同步异常工单状态信息至CRM失败!状态:" + crmStatusResponeEntity.getStatus()
													+ ",错误信息:" + crmStatusResponeEntity.getMessage());
										}
									}

									if (workOrderMap.get("OrderChannel").toString().equals("1")) {// CCI

									} else if (workOrderMap.get("OrderChannel").toString().equals("3")) {//DCEC
										if (workOrderMap.get("Comment").toString().contains("14")) {
											Map<String, Object> orderCommentInfo = crmServiceDao
													.getUserCommentInfoByOrderId(MapUtils.getLong(workOrderMap, "ID"));
											if (orderCommentInfo != null) {
												Map<String, Object> userCommentParameters = this
														.appWorkOrderUserCommentToCrmWorkOrderData(workOrderMap,
																orderCommentInfo);
												CRMResponeEntity crmUserCommentResponeEntity = CRMApiUtils
														.getCRMServiceApi().syncUserAppraisalInfoToCrm(
																crmOrderMap.get("serviceChannel").toString(),
																crmServiceDao, redisClientUtils, userCommentParameters);
												if (crmUserCommentResponeEntity.getStatus() != 0) {
													LOG.error("手动同步异常工单评价信息至CRM失败!状态:"
															+ crmUserCommentResponeEntity.getStatus() + ",错误信息:"
															+ crmUserCommentResponeEntity.getMessage());
												}

											}
										}
									}

								}
							}

						}
					} catch (Exception e) {
						e.printStackTrace();
						LOG.error("手动同步异常工单信息至CRM失败!错误信息:" + e.getMessage(), e);
						jsonObject.put("status", 1);
						jsonObject.put("msg", "异常工单同步失败：" + e.getMessage());
						jsonObject.put("data", new JSONObject());
						ParameterTool.writeResponse(response, jsonObject.toString());
					}
				} else {
					// 2 工单状态同步CRM异常
					workOrderMap = crmServiceDao.selectWorkOrderInfoByOrderNo(appOrderNo);
					if (workOrderMap != null) {
						String crmStationNo = "";
						Map<String, Object> ssRepairMap = new HashMap<>();
						ssRepairMap.put("serviceStationId", workOrderMap.get("ServiceStationId"));
						List<SSRepairT> ssRepairTS = serviceStationDao.getSSRepairListByServiceStaionId(ssRepairMap);
						if (ssRepairTS != null && ssRepairTS.size() > 0) {
							for (int j = 0; j < ssRepairTS.size(); j++) {
								SSRepairT ssRepairT = ssRepairTS.get(j);
								if (ssRepairT.getCompanyid().toString()
										.equals(workOrderMap.get("OrderChannel").toString())) {
									crmStationNo = ssRepairT.getBusinessno();
									break;
								}
							}
						}
						long companyId = MapUtils.getLongValue(workOrderMap, "OrderChannel", 0);
						CompanyT companyT = companyTDao.getCompanyInfoByCompanyID(companyId);
						UserT userT = loginDao.getUserByid(workOrderMap.get("Creator").toString());
						Map<String, Object> crmOrderMap = this.appWorkOrderToCrmWorkOrderData(workOrderMap,
								crmStationNo, companyT, userT);
						if (workOrderMap.get("Comment") != null
								&& workOrderMap.get("Comment").toString().length() > 0) {
							List<Map<String, Object>> orderStatusList = crmServiceDao
									.getAllWorkOrderStatusByOrderId(MapUtils.getLong(workOrderMap, "ID"));
							if (orderStatusList != null && orderStatusList.size() > 0) {
								for (int j = 0; j < orderStatusList.size(); j++) {
									Map<String, Object> orderStatusFlow = orderStatusList.get(j);
									if (MapUtils.getIntValue(orderStatusFlow, "processStatus", 0) <= 2) {
										continue; // 1、工单已创建  2、待区域经理确认
									}
									Map<String, Object> crmOrderStatusMap = this.appWorkOrderStatusToCrmWorkOrderData(
											workOrderMap, orderStatusFlow, crmStationNo);
									LOG.error(JsonUtils.toJsonString(crmOrderStatusMap));
									CRMResponeEntity crmStatusResponeEntity = CRMApiUtils.getCRMServiceApi()
											.syncOrderStatusToCrm(crmOrderMap.get("serviceChannel").toString(),
													crmServiceDao, redisClientUtils, crmOrderStatusMap,null);
									if (crmStatusResponeEntity.getStatus() != 0) {
										LOG.error("手动同步异常工单状态信息至CRM失败!状态:" + crmStatusResponeEntity.getStatus()
												+ ",错误信息:" + crmStatusResponeEntity.getMessage());
									}
								}

								if (workOrderMap.get("OrderChannel").toString().equals("1")) {// CCI

								} else if (workOrderMap.get("OrderChannel").toString().equals("3")) {//DCEC
									if (workOrderMap.get("Comment").toString().contains("14")) {
										Map<String, Object> orderCommentInfo = crmServiceDao
												.getUserCommentInfoByOrderId(MapUtils.getLong(workOrderMap, "ID"));
										if (orderCommentInfo != null) {
											Map<String, Object> userCommentParameters = this
													.appWorkOrderUserCommentToCrmWorkOrderData(workOrderMap,
															orderCommentInfo);
											CRMResponeEntity crmUserCommentResponeEntity = CRMApiUtils
													.getCRMServiceApi().syncUserAppraisalInfoToCrm(
															crmOrderMap.get("serviceChannel").toString(), crmServiceDao,
															redisClientUtils, userCommentParameters);
											if (crmUserCommentResponeEntity.getStatus() != 0) {
												LOG.error("手动同步异常工单评价信息至CRM失败!状态:"
														+ crmUserCommentResponeEntity.getStatus() + ",错误信息:"
														+ crmUserCommentResponeEntity.getMessage());
											}

										}
									}
								}

							}
						}
					} else {
						jsonObject.put("status", 1);
						jsonObject.put("msg", "工单号输入错误");
						jsonObject.put("data", "");
						ParameterTool.writeResponse(response, jsonObject.toString());
					}

				}

			} else {
				jsonObject.put("status", 1);
				jsonObject.put("msg", "请输入有效工单号");
				jsonObject.put("data", "");
				ParameterTool.writeResponse(response, jsonObject.toString());
			}

		} else {
			jsonObject.put("status", 1);
			jsonObject.put("msg", "请输入工单号");
			jsonObject.put("data", "");
			ParameterTool.writeResponse(response, jsonObject.toString());
		}

		return null;
	}

	//ljk   2.2.4 CRM系统同步工单状态到APP系统
	@Transactional
	@Override
	public ModelAndView syncCRMOrderStatus(Map<String, Object> httpMap) {
		HttpServletRequest request = (HttpServletRequest) httpMap.get("request");
		HttpServletResponse response = (HttpServletResponse) httpMap.get("response");

		String company = httpMap.get(CRMServiceConst.CRM_REQUEST_COMPANY).toString();// 渠道
		JSONObject jsonObject = new JSONObject(); // 返回定义
		int updateResult = -1;

        @SuppressWarnings("unchecked")    ////、、、、、、、、、、  转成map
		Map<String, Object> requestMap = (Map<String, Object>) JSONObject
				.fromObject(httpMap.get(CRMServiceConst.CRM_REQUEST_PARAMS).toString());

		// 更新发动机基础信息表的SMN
		if (requestMap.containsKey("SMN") && requestMap.get("SMN").toString().length() > 0) {
			Map<String, Object> engineMsgParamMap = new HashMap<>();
			engineMsgParamMap.put("ESN", MapUtils.getString(requestMap, "ESN", ""));
			Map<String, Object> engineMsgMap = crmServiceDao.getEngineMsgByESNAndChannel(engineMsgParamMap);
			if (engineMsgMap != null) {
				engineMsgMap.put("SMN", MapUtils.getString(requestMap, "SMN", ""));
				engineMsgDao.updateEngineMsg(engineMsgMap);
			}

		}
        //修改表单的市场类型和应用程序  //、、、、、、、、、、更新市场类型
		if (requestMap.containsKey("marketTypes") && requestMap.get("marketTypes").toString().length() > 0){
			//根据OrderNo修改市场类型
			if (requestMap.containsKey("orderNo") && requestMap.get("orderNo").toString().length() > 0){
				crmServiceDao.updateMarketTypes(requestMap.get("marketTypes").toString(),requestMap.get("orderNo").toString());
			}

		}
        //、、、、、、、、、、更新    applications
		if (requestMap.containsKey("applications") && requestMap.get("applications").toString().length() > 0){
			//根据OrderNo更改应用程序
			if (requestMap.containsKey("orderNo") && requestMap.get("orderNo").toString().length() > 0){
				crmServiceDao.updateApplication(requestMap.get("applications").toString(),requestMap.get("orderNo").toString());
			}
		}

		if (company.equals(CRMServiceConst.DBU)) {
            // 查询工单信息
			Map<String, Object> orderInfoMap = crmServiceDao
					.getOldOrderInfoByOrderNo(requestMap.get("orderNo").toString());
			if (orderInfoMap == null) {

				jsonObject.put("status", 1);
				jsonObject.put("msg", "APP工单号不存在，请检查APP工单号是否正确");
				jsonObject.put("data", new JSONObject());
				ParameterTool.writeResponse(response, jsonObject.toString());
				return null;
			}

            // 工单参数转化       、、、、、、、、更新后的参数
			Map<String, Object> updateOrderMap = CRMRequestMapToAppMapUtils.workOrderFieldUpdateFromDBU(orderInfoMap, requestMap);

			Integer scenarioStatus = MapUtils.getInteger(requestMap, "scenarioStatus");
			// 1、CAC远程解决
			if (scenarioStatus.equals(14) || scenarioStatus.equals(15) || scenarioStatus.equals(16)) {

				String currentTime = LocalTimeUtil.getRealCurrentTime();
				if (scenarioStatus.equals(14)) {//APP客户报修/APP服务商报修，CAC远程解决工单
					String customerPhone = MapUtils.getString(orderInfoMap, "CustomerPhone", "");

					List<UserT> customerUser = loginDao.getUserByPhone(customerPhone);
					if (customerUser != null && customerUser.size() > 0) {
						updateOrderMap.put("OrderStatus", "13");
						updateResult = crmServiceDao.updateAllWorkOrderInfoByDBU(updateOrderMap);
					} else {
						updateOrderMap.put("OrderStatus", "14");
						updateResult = crmServiceDao.updateAllWorkOrderInfoByDBU(updateOrderMap);
					}

					if (updateResult > 0) {

						this.saveOperationAndMessageRecords(updateOrderMap, currentTime, customerUser);
						this.sendInterfaceMessageToCRM(updateOrderMap, currentTime, customerUser, company);

						jsonObject.put("status", 0);
						jsonObject.put("msg", "工单状态更新成功");
						jsonObject.put("data", new JSONObject());
						ParameterTool.writeResponse(response, jsonObject.toString());
						return null;

					} else {
						LOG.error("工单信息更新失败" + JsonUtils.toJsonString(updateOrderMap));
						jsonObject.put("status", 1);
						jsonObject.put("msg", "工单信息更新失败");
						jsonObject.put("data", new JSONObject());
						ParameterTool.writeResponse(response, jsonObject.toString());
						return null;
					}
				} else if (scenarioStatus.equals(15)) { // 15、区域工程师异常关闭/服务商异常关闭，CAC远程解决工单
					Map<String, Object> newOrderMap = CRMRequestMapToAppMapUtils
							.newWorkOrderFieldCreateFromDBU(orderInfoMap, requestMap);
					//String OrderNo = workOrderRepairService.getOrderNo(updateOrderMap);// 后台自动生成工单编号
					/**
					 * <p>
					 *     自动生成工单编号，由 redis 更改为 sqlServer
					 * </p>
					 */
					String OrderNo = OrderGenerateUtil.getWorkOrderNo();
					newOrderMap.put("OrderNo", OrderNo);
					newOrderMap.put("OrderId", "");// 用户保存插入工单成功返回的工单ID

					String customerPhone = MapUtils.getString(orderInfoMap, "CustomerPhone", "");
					List<UserT> customerUser = loginDao.getUserByPhone(customerPhone);
					int saveResult = -1;
					if (customerUser != null && customerUser.size() > 0) {
						newOrderMap.put("OrderStatus", "13");
						newOrderMap.put("appAppraise", 1);
						saveResult = crmServiceDao.CreateWorkOrder(newOrderMap);
					} else {
						newOrderMap.put("OrderStatus", "14");
						newOrderMap.put("appAppraise", 0);
						saveResult = crmServiceDao.CreateWorkOrder(newOrderMap);
					}

					if (saveResult > 0) {
						this.saveOperationAndMessageRecords(newOrderMap, currentTime, customerUser);
						//                        this.sendInterfaceMessageToCRM(newOrderMap, currentTime, customerUser, company);

						JSONObject newOrderInfo = new JSONObject();
						newOrderInfo.put("APPOrderNo", newOrderMap.get("OrderNo"));
						newOrderInfo.put("billStatus", MapUtils.getIntValue(newOrderMap, "OrderStatus", 0));
						newOrderInfo.put("appAppraise", newOrderMap.get("appAppraise"));
						jsonObject.put("status", 0);
						jsonObject.put("msg", "工单状态更新成功");
						jsonObject.put("data", newOrderInfo);
						ParameterTool.writeResponse(response, jsonObject.toString());
						return null;
					} else {
						LOG.error("工单信息更新失败" + JsonUtils.toJsonString(newOrderMap));
						jsonObject.put("status", 1);
						jsonObject.put("msg", "工单信息更新失败");
						jsonObject.put("data", new JSONObject());
						ParameterTool.writeResponse(response, jsonObject.toString());
						return null;
					}
				} else if (scenarioStatus.equals(16)) { // 16、服务商拒绝工单，CAC远程解决工单

					Map<String, Object> newOrderMap = CRMRequestMapToAppMapUtils
							.newWorkOrderFieldCreateFromDBU(orderInfoMap, requestMap);
					//String OrderNo = workOrderRepairService.getOrderNo(updateOrderMap);// 后台自动生成工单编号
					/**
					 * <p>
					 *     自动生成工单编号，由 redis 更改为 sqlServer
					 * </p>
					 */
					String OrderNo = OrderGenerateUtil.getWorkOrderNo();
					newOrderMap.put("OrderNo", OrderNo);
					newOrderMap.put("OrderId", "");// 用户保存插入工单成功返回的工单ID
					newOrderMap.put("RelOrderIdOld", orderInfoMap.get("ID")); // 新工单绑定旧工单ID

					String customerPhone = MapUtils.getString(orderInfoMap, "CustomerPhone", "");
					List<UserT> customerUser = loginDao.getUserByPhone(customerPhone);
					int saveResult = -1;
					if (customerUser != null && customerUser.size() > 0) {
						newOrderMap.put("OrderStatus", "13");
						newOrderMap.put("appAppraise", 1);
						saveResult = crmServiceDao.CreateWorkOrder(newOrderMap);
					} else {
						newOrderMap.put("OrderStatus", "14");
						newOrderMap.put("appAppraise", 0);
						saveResult = crmServiceDao.CreateWorkOrder(newOrderMap);
					}

					/**
					 * 新旧工单关联
					 **/
					Map<String, Object> oldOrderInfoMap = new HashMap<>();
					oldOrderInfoMap.put("RelOrderId", newOrderMap.get("OrderId"));
					oldOrderInfoMap.put("oldOrderId", newOrderMap.get("RelOrderIdOld"));
					crmServiceDao.updateRelOrderId(oldOrderInfoMap);

					if (saveResult > 0) {
						this.saveOperationAndMessageRecords(newOrderMap, currentTime, customerUser);
						//                        this.sendInterfaceMessageToCRM(newOrderMap, currentTime, customerUser, company);

						JSONObject newOrderInfo = new JSONObject();
						newOrderInfo.put("APPOrderNo", newOrderMap.get("OrderNo"));
						newOrderInfo.put("billStatus", MapUtils.getIntValue(newOrderMap, "OrderStatus", 0));
						newOrderInfo.put("appAppraise", newOrderMap.get("appAppraise"));
						jsonObject.put("status", 0);
						jsonObject.put("msg", "工单状态更新成功");
						jsonObject.put("data", newOrderInfo);
						ParameterTool.writeResponse(response, jsonObject.toString());
						return null;
					} else {
						LOG.error("工单信息更新失败" + JsonUtils.toJsonString(newOrderMap));
						jsonObject.put("status", 1);
						jsonObject.put("msg", "工单信息更新失败");
						jsonObject.put("data", new JSONObject());
						ParameterTool.writeResponse(response, jsonObject.toString());
						return null;
					}
				}
				jsonObject.put("status", -1);
				jsonObject.put("msg", "工单状态更新失败");
				jsonObject.put("data", new JSONObject());
				ParameterTool.writeResponse(response, jsonObject.toString());
				return null;
			}

			// 将CRM传递数据转化成APP 后台字段
			if (requestMap.containsKey("isClosed") && requestMap.get("isClosed").toString().equals("1")) {// 取消工单

				updateOrderMap.put("OrderStatus", "22");
				updateResult = crmServiceDao.updateAllWorkOrderInfoByDBU(updateOrderMap);
				Long orderId = MapUtils.getLongValue(orderInfoMap, "ID", 0);
				//修改campaign任务状态
				updateCampaignStatus(orderId,5,-1L,"CAC已取消");
				//DBU渠道服务完成需要调用关闭主动升级工单接口
				//1: 服务工单异常关闭
				//2: 服务工单已取消
				//3: 服务工单已完成
				escalationService.disableEscalationByWorkOrderId(MapUtils.getLongValue(orderInfoMap, "ID", 0), 2);
				if (updateResult < 0) {
					LOG.error("工单信息更新失败" + JsonUtils.toJsonString(updateOrderMap));
					jsonObject.put("status", 1);
					jsonObject.put("msg", "工单信息更新失败");
					jsonObject.put("data", new JSONObject());
					ParameterTool.writeResponse(response, jsonObject.toString());
					return null;
				}
				// 取消工单记录操作记录表、发送消息和短息（客户）
				this.saveOperationAndMessageRecordsWithCloseAction(updateOrderMap, 1);

			} else {
				// APP服务商报修-CAC确认服务商通过
				if (updateOrderMap.get("scenarioStatus").toString().equals("10")) {
					int currentOrderStatus = MapUtils.getIntValue(orderInfoMap, "OrderStatus", -1);
					//sprint45 服务站报单  如果sf返回挂号失败   这里做个校验   挂号失败的工单这里不允许crm同步审核通过的状态
					if (currentOrderStatus == 39) {
						LOG.info("工单状态更新失败" + JsonUtils.toJsonString(updateOrderMap));
						jsonObject.put("status", 1);
						jsonObject.put("msg", "此工单已挂号失败，不允许再同步审核通过状态");
						jsonObject.put("data", new JSONObject());
						ParameterTool.writeResponse(response, jsonObject.toString());
						return null;
					}
					updateOrderMap.put("OrderStatus", "6"); // 6 待派服务技师

					updateResult = crmServiceDao.updateAllWorkOrderInfoByDBU(updateOrderMap);

					// 保存推荐三件服务站
					updateOrderMap.put("FirstStationId", -1);
					updateOrderMap.put("SecondStationId", -2);
					updateOrderMap.put("ThirdStationId", -3);
					int saveReStationResult = crmServiceDao.saveRecommendThreeStationToTable(updateOrderMap);
					if (saveReStationResult > 0) {
						LOG.info("推荐服务站保存成功");
					}
					{
						// 保存到WorkOrderOperatorRelationDao
						Map<String, Object> operatorRelationMap = new HashMap<>();
						operatorRelationMap.put("OrderId", updateOrderMap.get("OrderId"));
						operatorRelationMap.put("OrderStatus", updateOrderMap.get("OrderStatus"));
						operatorRelationMap.put("Name", updateOrderMap.get("DBEngineerName"));
						operatorRelationMap.put("Phone", updateOrderMap.get("DBEngineerPhone"));
						operatorRelationMap.put("Creator", 1);
						operatorRelationMap.put("CreateTime", updateOrderMap.get("CreateTime"));
						List<UserT> DBEngineerUsers = loginDao
								.getUserByPhone(operatorRelationMap.get("Phone").toString());
						if (DBEngineerUsers != null && DBEngineerUsers.size() > 0) {
							long DBEngineerUsersId = DBEngineerUsers.get(0).getId();
							operatorRelationMap.put("UserId", DBEngineerUsersId);
						}
						operatorRelationMap.put("Flag", 0);

						// TODO 把获取的区域工程师区域地址放入参数Map中
						crmPositionNameIntoMap(operatorRelationMap);

						operatorRelationDao.insertOperatorRelationInfo(operatorRelationMap);
					}

					if (updateResult < 0) {
						LOG.error("工单信息更新失败" + JsonUtils.toJsonString(updateOrderMap));
						jsonObject.put("status", 1);
						jsonObject.put("msg", "工单信息更新失败");
						jsonObject.put("data", new JSONObject());
						ParameterTool.writeResponse(response, jsonObject.toString());
						return null;
					}
					// 更新工单负责人表、信息提醒
					JSONObject result = this.saveWorkOrderPrincipalAndMessageInfoFromDBU(updateOrderMap);
					if (result != null) {
						ParameterTool.writeResponse(response, result.toString());
						result = null;
						return null;
					}
				}


                // APP服务商报修-CAC改派区域或者改派服务站
				if (updateOrderMap.get("scenarioStatus").toString().equals("8")
						|| updateOrderMap.get("scenarioStatus").toString().equals("9")) {
					updateOrderMap.put("OrderStatus", "20"); // 20 CAC关闭工单
					updateResult = crmServiceDao.updateAllWorkOrderInfoByDBU(updateOrderMap);

					if (updateResult < 0) {
						LOG.error("工单信息更新失败" + JsonUtils.toJsonString(updateOrderMap));
						jsonObject.put("status", 1);
						jsonObject.put("msg", "工单信息更新失败");
						jsonObject.put("data", new JSONObject());
						ParameterTool.writeResponse(response, jsonObject.toString());
						return null;
					}
					// 取消工单记录操作记录表、发送消息和短息（客户）
					this.saveOperationAndMessageRecordsWithCloseAction(updateOrderMap, 2);

				}
				// APP服务商报修-CAC改派区域或者改派服务站 or 服务商拒单，CAC指派区域或者指派服务站
				if (updateOrderMap.get("scenarioStatus").toString().equals("8")
						|| updateOrderMap.get("scenarioStatus").toString().equals("9")
						|| updateOrderMap.get("scenarioStatus").toString().equals("12")
						|| updateOrderMap.get("scenarioStatus").toString().equals("13")) {

					//String OrderNo = workOrderRepairService.getOrderNo(updateOrderMap);// 后台自动生成工单编号
					/**
					 * <p>
					 *     自动生成工单编号，由 redis 更改为 sqlServer
					 * </p>
					 */
					String OrderNo = OrderGenerateUtil.getWorkOrderNo();
					updateOrderMap.put("OrderNo", OrderNo);
					updateOrderMap.put("OrderId", "");// 用户保存插入工单成功返回的工单ID
					updateOrderMap.put("RelOrderIdOld", updateOrderMap.get("ID"));

					if (updateOrderMap.get("scenarioStatus").toString().equals("12")
							|| updateOrderMap.get("scenarioStatus").toString().equals("13")
							|| updateOrderMap.get("scenarioStatus").toString().equals("8")
							|| updateOrderMap.get("scenarioStatus").toString().equals("9")) {
						updateOrderMap.put("OrderSource", 2);// 设置工单来源为CAC指派

					}

					if (updateOrderMap.get("scenarioStatus").toString().equals("8")
							|| updateOrderMap.get("scenarioStatus").toString().equals("12")) {//指派了区域工程师
						updateOrderMap.put("GuessDistance", 0.0); // 18 待区域工程师处理 没有距离信息
						updateOrderMap.put("OrderStatus", "18"); // 18 待区域工程师处理
						updateOrderMap.put("ServiceStationId", -1);
						// 设置推荐服务站的默认值
						updateOrderMap.put("FirstStationId", -1);
						updateOrderMap.put("SecondStationId", -2);
						updateOrderMap.put("ThirdStationId", -3);

						List<Map<String, Object>> serviceStationList = (List<Map<String, Object>>) requestMap
								.get("stations");
						if (serviceStationList != null && serviceStationList.size() > 0) {
							for (int i = 0; i < serviceStationList.size(); i++) {
								Map<String, Object> threeSSMap = new HashMap<>();
								Map<String, Object> serviceStationMap = serviceStationList.get(i);
								threeSSMap.put("BusinessNo", serviceStationMap.get("stationNo"));
								threeSSMap.put("CompanyNo", company);
								ServiceStationT serviceStation = crmServiceDao
										.getServiceStationByBusinessNoAndCompanyNo(threeSSMap);
								if (serviceStation != null) {
									if (i == 0) {
										updateOrderMap.put("FirstStationId", serviceStation.getId());
									} else if (i == 1) {
										updateOrderMap.put("SecondStationId", serviceStation.getId());
									} else {
										updateOrderMap.put("ThirdStationId", serviceStation.getId());
									}
								}
							}
						}

						// 保存新工单
						int saveResult = crmServiceDao.CreateWorkOrder(updateOrderMap);
						// 保存推荐的三家服务商与工单关系
						if (saveResult > 0) {
							int saveReStationResult = crmServiceDao.saveRecommendThreeStationToTable(updateOrderMap);
							if (saveReStationResult > 0) {
								LOG.info("推荐服务站保存成功");
							}
							{
								// 保存到WorkOrderOperatorRelationDao
								Map<String, Object> operatorRelationMap = new HashMap<>();
								operatorRelationMap.put("OrderId", updateOrderMap.get("OrderId"));
								operatorRelationMap.put("OrderStatus", updateOrderMap.get("OrderStatus"));
								operatorRelationMap.put("Name", updateOrderMap.get("DBEngineerName"));
								operatorRelationMap.put("Phone", updateOrderMap.get("DBEngineerPhone"));
								operatorRelationMap.put("Creator", 1);
								operatorRelationMap.put("CreateTime", updateOrderMap.get("CreateTime"));
								List<UserT> DBEngineerUsers = loginDao
										.getUserByPhone(operatorRelationMap.get("Phone").toString());
								if (DBEngineerUsers != null && DBEngineerUsers.size() > 0) {
									long DBEngineerUsersId = DBEngineerUsers.get(0).getId();
									operatorRelationMap.put("UserId", DBEngineerUsersId);
								}
								operatorRelationMap.put("Flag", 0);

								// TODO 把获取的区域工程师区域地址放入参数Map中
								crmPositionNameIntoMap(operatorRelationMap);

								operatorRelationDao.insertOperatorRelationInfo(operatorRelationMap);
							}
							/**
							 * 新旧工单关联
							 **/
							Map<String, Object> oldOrderInfoMap = new HashMap<>();
							oldOrderInfoMap.put("RelOrderId", updateOrderMap.get("OrderId"));
							oldOrderInfoMap.put("oldOrderId", updateOrderMap.get("RelOrderIdOld"));
							crmServiceDao.updateRelOrderId(oldOrderInfoMap);

						}

					} else {

					    /**
					     * Tag=9,13
					     * scenarioStatus 9,13
					     */
						updateOrderMap.put("OrderStatus", "4"); // 4 待服务商接单
						updateOrderMap.put("AssignStationTime", LocalTimeUtil.getRealCurrentTime());
						List<Map<String, Object>> serviceStationList = (List<Map<String, Object>>) updateOrderMap
								.get("stations");
						if (serviceStationList != null && serviceStationList.size() > 0) {
							Map<String, Object> assignServiceStationMap = new HashMap<>();
							Map<String, Object> serviceStationMap = serviceStationList.get(0);
							assignServiceStationMap.put("BusinessNo", serviceStationMap.get("stationNo"));
							assignServiceStationMap.put("CompanyNo", company);
							ServiceStationT serviceStation = crmServiceDao
									.getServiceStationByBusinessNoAndCompanyNo(assignServiceStationMap);
							if (serviceStation == null || serviceStation.getId() < 0) {
								LOG.info("服务站信息没有查询到");
								jsonObject.put("status", 1);
								jsonObject.put("msg", "服务站基础信息未查询到");
								jsonObject.put("data", new JSONObject());
								ParameterTool.writeResponse(response, jsonObject.toString());
								return null;
							}
							updateOrderMap.put("ServiceStationId", serviceStation.getId().toString());

							/**
							 * TODO MT2.0需求
							 * 如果400同步的服务站为虚拟服务站(用于创建MT单子的服务站)则给当前服务工单设置MT标签
							 */
							String businessNo = MapUtils.getString(serviceStationMap, "stationNo", "");
							String stationName = MapUtils.getString(serviceStationMap, "stationName", "");
							// 如果指派的服务站匹配2个条件之一，则当前服务站就为虚拟服务站(MT服务站)
							if(Objects.equals(this.stationNo, businessNo) || Objects.equals(this.stationName, stationName)) {
								// MtTag默认为0，1：表示当前服务工单为移动
								updateOrderMap.put("MtTag", 1);
							}



							/**
							 * 8、CRM同步功能单，一定会指派服务站（故障点到服务站的距离要计算一下）
							 */
							Map<String, Object> StationLatLon = workOrderRePairDao.getDistance(updateOrderMap);
							// 获取距离和服务站经纬度
							String stationlonlat = StationLatLon.get("PositionLon") + ","
									+ StationLatLon.get("PositionLat");
							String Faultlonlat = updateOrderMap.get("LocLon") + "," + updateOrderMap.get("LocLat");
							Double distance = 0.0;
							try {
								distance = GetDistance.getDistance(stationlonlat, Faultlonlat);
								updateOrderMap.put("GuessDistance", distance);
							} catch (Exception e) {
								LOG.error("GuessDistance", e);
								// 获取故障点与服务站距离有误
								jsonObject.put("status", 1);
								jsonObject.put("msg", SMSEnum.type29.getName());
								jsonObject.put("data", "");
								ParameterTool.writeResponse(response, jsonObject.toString());
								return null;
							}
						} else {
							LOG.info("指派服务站为空");
							jsonObject.put("status", 1);
							jsonObject.put("msg", "指派服务站为空");
							jsonObject.put("data", new JSONObject());
							ParameterTool.writeResponse(response, jsonObject.toString());
							return null;
						}
						// 保存新工单
						int saveResult = crmServiceDao.CreateWorkOrder(updateOrderMap);
						if (saveResult > 0) {
							{
								// 保存到WorkOrderOperatorRelationDao
								Map<String, Object> operatorRelationMap = new HashMap<>();
								operatorRelationMap.put("OrderId", updateOrderMap.get("OrderId"));
								operatorRelationMap.put("OrderStatus", updateOrderMap.get("OrderStatus"));
								operatorRelationMap.put("Name", updateOrderMap.get("DBEngineerName"));
								operatorRelationMap.put("Phone", updateOrderMap.get("DBEngineerPhone"));
								operatorRelationMap.put("Creator", 1);
								operatorRelationMap.put("CreateTime", updateOrderMap.get("CreateTime"));
								List<UserT> DBEngineerUsers = loginDao
										.getUserByPhone(operatorRelationMap.get("Phone").toString());
								if (DBEngineerUsers != null && DBEngineerUsers.size() > 0) {
									long DBEngineerUsersId = DBEngineerUsers.get(0).getId();
									operatorRelationMap.put("UserId", DBEngineerUsersId);
								}
								operatorRelationMap.put("Flag", 0);
								// TODO 把获取的区域工程师区域地址放入参数Map中
								crmPositionNameIntoMap(operatorRelationMap);
								operatorRelationDao.insertOperatorRelationInfo(operatorRelationMap);
							}
							/**
							 * 新旧工单关联
							 **/
							Map<String, Object> oldOrderInfoMap = new HashMap<>();
							oldOrderInfoMap.put("RelOrderId", updateOrderMap.get("OrderId"));
							oldOrderInfoMap.put("oldOrderId", updateOrderMap.get("RelOrderIdOld"));
							crmServiceDao.updateRelOrderId(oldOrderInfoMap);
						}

					}

				} else {

					if (updateOrderMap.get("scenarioStatus").toString().equals("5")) {
						updateOrderMap.put("OrderStatus", "18"); // 18 待区域工程师处理
						updateOrderMap.put("ServiceStationId", -1);
						// 设置推荐服务站的默认值
						updateOrderMap.put("FirstStationId", -1);
						updateOrderMap.put("SecondStationId", -2);
						updateOrderMap.put("ThirdStationId", -3);

						{
							// 保存到WorkOrderOperatorRelationDao
							Map<String, Object> operatorRelationMap = new HashMap<>();
							operatorRelationMap.put("OrderId", updateOrderMap.get("OrderId"));
							operatorRelationMap.put("OrderStatus", updateOrderMap.get("OrderStatus"));
							operatorRelationMap.put("Name", updateOrderMap.get("DBEngineerName"));
							operatorRelationMap.put("Phone", updateOrderMap.get("DBEngineerPhone"));
							operatorRelationMap.put("Creator", 1);
							operatorRelationMap.put("CreateTime", updateOrderMap.get("CreateTime"));
							List<UserT> DBEngineerUsers = loginDao
									.getUserByPhone(operatorRelationMap.get("Phone").toString());
							if (DBEngineerUsers != null && DBEngineerUsers.size() > 0) {
								long DBEngineerUsersId = DBEngineerUsers.get(0).getId();
								operatorRelationMap.put("UserId", DBEngineerUsersId);
							}
							operatorRelationMap.put("Flag", 0);
							// TODO 把获取的区域工程师区域地址放入参数Map中
							crmPositionNameIntoMap(operatorRelationMap);
							operatorRelationDao.insertOperatorRelationInfo(operatorRelationMap);
						}

						@SuppressWarnings("unchecked")
						List<Map<String, Object>> serviceStationList = JSONArray
								.fromObject(updateOrderMap.get("stations").toString());
						if (serviceStationList != null && serviceStationList.size() > 0) {
							for (int i = 0; i < serviceStationList.size(); i++) {
								Map<String, Object> threeSSMap = new HashMap<>();
								Map<String, Object> serviceStationMap = serviceStationList.get(i);
								threeSSMap.put("BusinessNo", serviceStationMap.get("stationNo"));
								threeSSMap.put("CompanyNo", updateOrderMap.get("CompanyNo"));
								ServiceStationT serviceStation = crmServiceDao
										.getServiceStationByBusinessNoAndCompanyNo(threeSSMap);
								if (serviceStation != null) {
									if (i == 0) {
										updateOrderMap.put("FirstStationId", serviceStation.getId());
									} else if (i == 1) {
										updateOrderMap.put("SecondStationId", serviceStation.getId());
									} else {
										updateOrderMap.put("ThirdStationId", serviceStation.getId());
									}
								}

							}
						}
						int saveReStationResult = crmServiceDao.saveRecommendThreeStationToTable(updateOrderMap);
						if (saveReStationResult > 0) {
							LOG.info("推荐服务站保存成功");
						}

						String engineerPhone = updateOrderMap.get("DBEngineerPhone").toString();
						List<UserT> userList = loginDao.getUserByPhone(engineerPhone);
						if (userList != null && userList.size() > 0) {
							updateOrderMap.put("PrincipalId", userList.get(0).getId());
							updateResult = crmServiceDao.updateAllWorkOrderInfoByDBU(updateOrderMap);
							if (updateResult < 0) {

								LOG.error("工单信息更新失败" + JsonUtils.toJsonString(updateOrderMap));
								jsonObject.put("status", 1);
								jsonObject.put("msg", "工单信息更新失败");
								jsonObject.put("data", new JSONObject());
								ParameterTool.writeResponse(response, jsonObject.toString());
								return null;
							}
						} else {

							LOG.error("区域工程师在APP系统未创建" + JsonUtils.toJsonString(updateOrderMap));
							jsonObject.put("status", 1);
							jsonObject.put("msg", "区域工程师在APP系统未创建");
							jsonObject.put("data", new JSONObject());
							ParameterTool.writeResponse(response, jsonObject.toString());
							return null;
						}

					} else if (updateOrderMap.get("scenarioStatus").toString().equals("17")) {
						//dbu服务站报单，sf校验中的状态信息检查中
						updateOrderMap.put("OrderStatus", "40"); // 40 信息检查中
						updateResult = crmServiceDao.updateAllWorkOrderInfoByDBU(updateOrderMap);
                        // 1、记录用户行为日志（需要把上面保存成功的工单Id放进map中）
						workOrderTServiceImpl.saveOperation(MapUtils.getLongValue(updateOrderMap, "OrderId", 0), -1,
								MapUtils.getIntValue(updateOrderMap, "OrderStatus", 0), "信息检查中", "0.00", "0.00", "", "", 0, -1, LocalTimeUtil.getRealCurrentTime());
						JSONObject obj = new JSONObject();
						obj.put("APPOrderNo", updateOrderMap.get("OrderNo"));

						JSONObject jsonObject1 = new JSONObject();
						jsonObject1.put("data", obj);
						jsonObject1.put("status", 0);
						jsonObject1.put("msg", "");
						ParameterTool.writeResponse(response, jsonObject1.toString());
						return null;
					}  else if (updateOrderMap.get("scenarioStatus").toString().equals("18")) {
						String currentTime = LocalTimeUtil.getRealCurrentTime();
						//dbu服务站报单，sf校验中的状态挂号失败
						updateOrderMap.put("OrderStatus", "39"); // 39 挂号失败
						String rejectedReason = MapUtils.getString(updateOrderMap,"rejectedReason","");
						updateResult = crmServiceDao.updateAllWorkOrderInfoByDBU(updateOrderMap);
						// 1、记录用户行为日志（需要把上面保存成功的工单Id放进map中）
						workOrderTServiceImpl.saveOperation(MapUtils.getLongValue(updateOrderMap, "OrderId", 0), -1,
								MapUtils.getIntValue(updateOrderMap, "OrderStatus", 0), StringUtils.isBlank(rejectedReason) ? "挂号失败" : rejectedReason, "0.00", "0.00", "", "", 0, -1, currentTime);
						JSONObject obj = new JSONObject();
						obj.put("APPOrderNo", updateOrderMap.get("OrderNo"));

						int orderSource = MapUtils.getIntValue(orderInfoMap, "OrderSource", -1);
						if (orderSource == 1) {
							Long userId = MapUtils.getLongValue(orderInfoMap, "Creator", -1);
							UserT userT = userTDao.selectById(userId);
							if(null != userT){
								String userPhone = userT.getPhone();
								String userName = userT.getUserName();
								//3.推送短信和app提醒给经销商站长（报单人员）
								String content = "您的服务工单" + updateOrderMap.get("OrderNo") + "，";
								WorkOrderT workOrderT = workOrderTDao.getWorkOrderByOrderId(MapUtils.getLongValue(updateOrderMap, "OrderId"));
								if(workOrderT.getOrderChannel() == 1){
									content = content + "属于\"" + workOrderT.getSellType() + "\"" + (StringUtils.isNotBlank(workOrderT.getServiceSubtype()) ? "-" + workOrderT.getServiceSubtype() : "") + "，";
								}
								content = content + "挂号失败";
								if(StringUtils.isNotBlank(rejectedReason)){
									content = content + "，失败原因：" + rejectedReason;
								}
								String smsResult = SmsUtils.sendMessage(userPhone, content);
								//4.保存推送记录表
								List<Map<String, Object>> notifyRecordList = new ArrayList<>();
								Map<String, Object> smsNotifyRecord = workOrderTServiceImpl.saveMsgOperation(MapUtils.getLongValue(orderInfoMap, "ID"), 2, 1, userId, content, 1, currentTime, String.format("%s发送状态:%s", userPhone, smsResult), userId);
								notifyRecordList.add(smsNotifyRecord);
								if (com.cci.kangdao.utilTool.CollectionUtils.isNotEmpty(notifyRecordList)) {
									workOrderRePairDao.saveMsgOperation(notifyRecordList);
								}
								//推送app提醒并入库
								noticeService.push(2, 1,MapUtils.getLongValue(orderInfoMap, "ID"), userId, userName, "新工单提醒",
										content, content, userId);
							}
						}
						JSONObject jsonObject1 = new JSONObject();
						jsonObject1.put("data", obj);
						jsonObject1.put("status", 0);
						jsonObject1.put("msg", "");
						ParameterTool.writeResponse(response, jsonObject1.toString());
						return null;
					} else {

						updateOrderMap.put("OrderStatus", "4"); // 4 待服务商接单
						updateOrderMap.put("AssignStationTime", LocalTimeUtil.getRealCurrentTime());

						{
							// 保存到WorkOrderOperatorRelationDao
							Map<String, Object> operatorRelationMap = new HashMap<>();
							operatorRelationMap.put("OrderId", updateOrderMap.get("OrderId"));
							operatorRelationMap.put("OrderStatus", updateOrderMap.get("OrderStatus"));
							operatorRelationMap.put("Name", updateOrderMap.get("DBEngineerName"));
							operatorRelationMap.put("Phone", updateOrderMap.get("DBEngineerPhone"));
							operatorRelationMap.put("Creator", 1);
							operatorRelationMap.put("CreateTime", updateOrderMap.get("CreateTime"));
							List<UserT> DBEngineerUsers = loginDao
									.getUserByPhone(operatorRelationMap.get("Phone").toString());
							if (DBEngineerUsers != null && DBEngineerUsers.size() > 0) {
								long DBEngineerUsersId = DBEngineerUsers.get(0).getId();
								operatorRelationMap.put("UserId", DBEngineerUsersId);
							}
							operatorRelationMap.put("Flag", 0);
							// TODO 把获取的区域工程师区域地址放入参数Map中
							crmPositionNameIntoMap(operatorRelationMap);
							operatorRelationDao.insertOperatorRelationInfo(operatorRelationMap);
						}

						@SuppressWarnings("unchecked")
						List<Map<String, Object>> serviceStationList = JSONArray
								.fromObject(updateOrderMap.get("stations").toString());
						if (serviceStationList != null && serviceStationList.size() > 0) {
							Map<String, Object> serviceStationMap = serviceStationList.get(0);
							updateOrderMap.put("BusinessNo", serviceStationMap.get("stationNo"));
							ServiceStationT serviceStation = crmServiceDao
									.getServiceStationByBusinessNoAndCompanyNo(updateOrderMap);
							if (serviceStation == null || serviceStation.getId() < 0) {
								LOG.info("服务站信息没有查询到");
								jsonObject.put("status", 1);
								jsonObject.put("msg", "服务站基础信息未查询到");
								jsonObject.put("data", new JSONObject());
								ParameterTool.writeResponse(response, jsonObject.toString());
								return null;
							}
							updateOrderMap.put("ServiceStationId", serviceStation.getId().toString());

							/**
							 * TODO MT2.0需求
							 * 如果400同步的服务站为虚拟服务站(用于创建MT单子的服务站)则给当前服务工单设置MT标签
							 */
							String businessNo = MapUtils.getString(serviceStationMap, "stationNo", "");
							String stationName = MapUtils.getString(serviceStationMap, "stationName", "");
							// 如果指派的服务站匹配2个条件之一，则当前服务站就为虚拟服务站(MT服务站)
							if(Objects.equals(this.stationNo, businessNo) || Objects.equals(this.stationName, stationName)) {
								// MtTag默认为0，1：表示当前服务工单为移动
								updateOrderMap.put("MtTag", 1);
							}


							/**
							 * 8、CRM同步功能单，一定会指派服务站（故障点到服务站的距离要计算一下）
							 */
							Map<String, Object> StationLatLon = workOrderRePairDao.getDistance(updateOrderMap);
							// 获取距离和服务站经纬度
							String stationlonlat = StationLatLon.get("PositionLon") + ","
									+ StationLatLon.get("PositionLat");
							String Faultlonlat = updateOrderMap.get("LocLon") + "," + updateOrderMap.get("LocLat");
							Double distance = 0.0;
							try {
								distance = GetDistance.getDistance(stationlonlat, Faultlonlat);
								updateOrderMap.put("GuessDistance", distance);
								updateResult = crmServiceDao.updateAllWorkOrderInfoByDBU(updateOrderMap);
								if (updateResult < 0) {
									LOG.error("工单信息更新失败" + JsonUtils.toJsonString(updateOrderMap));
									jsonObject.put("status", 1);
									jsonObject.put("msg", "工单信息更新失败");
									jsonObject.put("data", new JSONObject());
									ParameterTool.writeResponse(response, jsonObject.toString());
								}
							} catch (Exception e) {
								LOG.error("GuessDistance", e);
								// 获取故障点与服务站距离有误
								jsonObject.put("status", 1);
								jsonObject.put("msg", SMSEnum.type29.getName());
								jsonObject.put("data", new JSONObject());
								ParameterTool.writeResponse(response, jsonObject.toString());
								return null;
							}
						} else {
							LOG.info("指派服务站不存在");
							jsonObject.put("status", 1);
							jsonObject.put("msg", "指派服务站不存在");
							jsonObject.put("data", new JSONObject());
							ParameterTool.writeResponse(response, jsonObject.toString());
							return null;
						}
					}

				}
				// 更新工单负责人表、信息提醒
				JSONObject result = this.saveWorkOrderPrincipalAndMessageInfoFromDBU(updateOrderMap);
				if (result != null) {
					ParameterTool.writeResponse(response, result.toString());
					result = null;
					return null;
				}
			}

			// APP服务商报修-CAC改派区域或者改派服务站 or 服务商拒单，CAC指派区域或者指派服务站
			if (updateOrderMap.get("scenarioStatus").toString().equals("8")
					|| updateOrderMap.get("scenarioStatus").toString().equals("9")
					|| updateOrderMap.get("scenarioStatus").toString().equals("12")
					|| updateOrderMap.get("scenarioStatus").toString().equals("13")) {

				JSONObject newOrderInfo = new JSONObject();
				newOrderInfo.put("APPOrderNo", updateOrderMap.get("OrderNo"));
				jsonObject.put("status", 0);
				jsonObject.put("msg", "工单状态更新成功");
				jsonObject.put("data", newOrderInfo);
			} else {
				jsonObject.put("status", 0);
				jsonObject.put("msg", "工单状态更新成功");
				jsonObject.put("data", new JSONObject());
			}
			ParameterTool.writeResponse(response, jsonObject.toString());
			return null;
		}

		return null;
	}



	//sf修改campaign任务状态
	void updateCampaignStatus(Long orderId,Integer status,Long userId,String remark){
		//查看当前工单是否存在campaign任务
		List<Map<String,Object>> campaignList = campaignTaskInfoDao.getCampaignListByOrderId(orderId);
		if(CollectionUtils.isNotEmpty(campaignList)){
			String currentTime = LocalTimeUtil.getRealCurrentTime();
			//修改campaign任务状态
			campaignTaskInfoDao.updateCampaignTaskStatus(status,userId,currentTime,orderId);
			//插入操作记录表
			for(Map<String,Object> campaign : campaignList){
				CampaignTaskFlow campaignTaskFlow = new CampaignTaskFlow();
				campaignTaskFlow.setCampaignTaskInfoId(MapUtils.getLongValue(campaign,"id"));
				campaignTaskFlow.setCampaignTaskStatus(status);
				campaignTaskFlow.setRemark(remark);
				campaignTaskFlowDao.insert(campaignTaskFlow,userId,currentTime);
			}
		}
	}



	/**
	 * 根据手机号查询出区域工程师对应的区域
	 */
	private String getCrmPositionNameByPhone(String phone) {
		if (StringUtils.isNotBlank(phone)) {
			return positionUserTDao.getCrmPositionNameByPhone(phone);
		}
		return null;
	}

	/**
	 * 把区域工程师的区域地址放入map参数中
	 */
	private void crmPositionNameIntoMap(Map<String, Object> operatorRelationMap) {
		// 获取区域工程师的区域地址
		Object phoneObj = operatorRelationMap.get("Phone");
		String crmPositionName = getCrmPositionNameByPhone(phoneObj == null ? null : phoneObj.toString());
		operatorRelationMap.put("CrmPositionName", crmPositionName);
	}

	@Override
	@SuppressWarnings("unchecked")
	public void syncCrmOrderStatusFromCCEC(Map<String, Object> map) {
		String interfaceName = "syncAppWorkOrderStatus";
		HttpServletResponse response = (HttpServletResponse) map.get("response");
		String companyNo = MapUtils.getString(map, CRMServiceConst.CRM_REQUEST_COMPANY);
		String paramString = MapUtils.getString(map, CRMServiceConst.CRM_REQUEST_PARAMS);
		Map<String, Object> requestMap = new HashMap<>();
		if (StringUtils.isNotEmpty(paramString)) {
			requestMap = JsonUtils.toJavaObject(paramString, Map.class);
		}

		CompanyT companyT = companyTDao.getCompanyInfoByCompanyNo(companyNo);
		if (CRMServiceConst.CCEC.equals(companyNo)) {
			String orderNo = MapUtils.getString(requestMap, "orderNo");
			Map<String, Object> orderInfoMap = crmServiceDao.getOldOrderInfoByOrderNo(orderNo);
			if (MapUtils.isEmpty(orderInfoMap)) {
				String message = "APP工单号不存在，请检查APP工单号是否正确";
				ParameterTool.writeResponse(response, 1, message);
				saveToAPIExceptionT(interfaceName, message, JsonUtils.toJsonString(requestMap), companyNo);
				return;
			}
			Long orderId = MapUtils.getLong(orderInfoMap, "ID");
			// 工单参数转化
			Map<String, Object> updateOrderMap = convertOrderStatusInfoFromCCEC(companyT, orderInfoMap, requestMap);
			updateOrderMap.put("ID", orderId);
			String billStatus = MapUtils.getString(updateOrderMap, "billStatus");
			if (billStatus.equals("4")) {
				// 待服务商接单状态
				String stationNo = MapUtils.getString(updateOrderMap, "stationNo");
				ServiceStationT serviceStationT = serviceStationDao.getServiceStationByStationNo(companyT.getId(),
						stationNo);
				if (null != serviceStationT) {

					Long dataStationId = MapUtils.getLong(orderInfoMap, "ServiceStationId", 0L);
					// 原serviceStationId不为空,需要确认是指派服务商还是改派服务商
					if (NumberUtils.isPositiveNum(dataStationId)) {
						// 不是同一服务商，做改派逻辑
						if (!dataStationId.equals(serviceStationT.getId())) {
							// 重新生成新工单
							//orderNo = workOrderRepairService.getOrderNo(new HashMap<>(0));
							/**
							 * <p>
							 *     自动生成工单编号，由 redis 更改为 sqlServer
							 * </p>
							 */
							orderNo = OrderGenerateUtil.getWorkOrderNo();
							// 移除原工单的混淆数据
							orderInfoMap.remove("GoOutType");
							orderInfoMap.remove("ServiceCarId");
							orderInfoMap.remove("ServiceCarNo");

							orderInfoMap.put("OrderNo", orderNo);
							orderInfoMap.put("CCSSOrderNo", MapUtils.getString(updateOrderMap, "CCSSOrderNo"));
							orderInfoMap.put("ServiceStationId", serviceStationT.getId());
							String currentTime = LocalTimeUtil.getRealCurrentTime();
							Double guessDistance = getGuessDistance(serviceStationT.getId(),
									MapUtils.getString(orderInfoMap, "LocLon"),
									MapUtils.getString(orderInfoMap, "LocLat"));
							orderInfoMap.put("GuessDistance", guessDistance);
							orderInfoMap.put("AssignStationTime", currentTime);
							orderInfoMap.put("RelOrderIdOld", orderId);
							orderInfoMap.put("OrderStatus", Dictionaries.OrderStatus_04.getIndex());
							workOrderRePairDao.CreateWorkOrder(orderInfoMap);
							// 获取新工单ID
							Long newOrderId = MapUtils.getLong(orderInfoMap, "OrderId");
							// 获取服务站站长/信息员
							List<UserT> userTList = userTDao
									.getStationMasterListByServiceStationId(serviceStationT.getId());
							String ccssOrderNo = MapUtils.getString(orderInfoMap, "CCSSOrderNo");
							String sendMessage = String.format("您有新工单信息，工单号%s，请尽快处理。",
									StringUtils.isEmpty(ccssOrderNo) ? orderNo : orderNo + "（FW号" + ccssOrderNo + "）");
							sendMassageInfo(newOrderId, userTList, 3, 2, 1, sendMessage, -1L);
							saveOrderFlowFromCRM(newOrderId, Dictionaries.OrderStatus_04.getIndex(),
									"CRM改派经销商，新工单待服务商接单");

							// 原工单设置为400异常已关闭
							Map<String, Object> closeOrderMap = new HashMap<>();
							closeOrderMap.put("ID", orderId);
							closeOrderMap.put("OrderStatus", Dictionaries.OrderStatus_29.getIndex());
							closeOrderMap.put("UpdateTime", LocalTimeUtil.getRealCurrentTime());
							closeOrderMap.put("RelOrderId", newOrderId);
							workOrderTDao.updateByPrimaryKeySelective(closeOrderMap);
							saveOrderFlowFromCRM(orderId, Dictionaries.OrderStatus_29.getIndex(), "CRM改派经销商，原工单400关闭");
						} else {
							// 同一经销商，直接接单并通知待技师接单状态
							// 将工单状态置为待派服务技师
							updateOrderMap.put("OrderStatus", Dictionaries.OrderStatus_06.getIndex());
							String currentTime = LocalTimeUtil.getRealCurrentTime();
							updateOrderMap.put("AssignStationTime", currentTime);
							updateOrderMap.put("AssignEngineerTime", currentTime);
							updateOrderMap.put("ReceiveTimeStation", currentTime);
							updateOrderMap.put("Updator", -1);
							updateOrderMap.put("UpdateTime", currentTime);
							workOrderTDao.updateByPrimaryKeySelective(updateOrderMap);
							// 获取服务站站长/信息员
							List<UserT> userTList = userTDao
									.getStationMasterListByServiceStationId(serviceStationT.getId());
							String ccssOrderNo = MapUtils.getString(orderInfoMap, "CCSSOrderNo");
							String sendMessage = String.format("您有新的工单待指派，工单号%s，请尽快处理。",
									StringUtils.isBlank(ccssOrderNo) ? orderNo : orderNo + "（FW号" + ccssOrderNo + "）");
							sendMassageInfo(orderId, userTList, 3, 2, 1, sendMessage, -1L);

							// 给客户发送短信
							String sendUserMessage = String.format("您的工单已有服务商接单，工单号%s，请查看。", orderNo);
							String customerPhone = MapUtils.getString(orderInfoMap, "CustomerPhone");
							if (StringUtils.isNotEmpty(customerPhone)) {
								UserT userT = userTDao.getUserByPhone(customerPhone);
								if (null != userT) {
									sendMassageInfo(orderId, userT, 3, 2, 1, sendUserMessage, -1L);
								}
							}

							// 保存流水信息
							saveOrderFlowFromCRM(orderId, Dictionaries.OrderStatus_04.getIndex(), "CRM指派经销商");
							saveOrderFlowFromCRM(orderId, Dictionaries.OrderStatus_06.getIndex(), "CRM指派经销商,默认服务商接单");

							Map<String, Object> data = new HashMap<>();
							data.put("APPOrderNo", orderNo);
							ParameterTool.writeSuccessResponse(response, data);
							// TODO: 2020/3/12 发送待派技师状态给CRM
							asyncCrmService.syncStatusToCCEC(orderNo, Dictionaries.OrderStatus_06.getIndex());
						}
						// 逻辑结束，响应前端
						Map<String, Object> data = new HashMap<>();
						data.put("APPOrderNo", orderNo);
						ParameterTool.writeSuccessResponse(response, data);
					} else {
						// 关联工单服务站信息
						updateOrderMap.put("ServiceStationId", serviceStationT.getId());
						// 将工单状态置为待服务商接单
						updateOrderMap.put("OrderStatus", Dictionaries.OrderStatus_04.getIndex());
						String currentTime = LocalTimeUtil.getRealCurrentTime();
						updateOrderMap.put("AssignStationTime", currentTime);
						updateOrderMap.put("AssignEngineerTime", currentTime);
						updateOrderMap.put("Updator", -1);
						updateOrderMap.put("UpdateTime", currentTime);
						workOrderTDao.updateByPrimaryKeySelective(updateOrderMap);
						// 获取服务站站长/信息员
						List<UserT> userTList = userTDao
								.getStationMasterListByServiceStationId(serviceStationT.getId());
						String ccssOrderNo = MapUtils.getString(orderInfoMap, "CCSSOrderNo");
						String sendMessage = String.format("您有新工单信息，工单号%s，请尽快处理。",
								StringUtils.isBlank(ccssOrderNo) ? orderNo : orderNo + "（FW号" + ccssOrderNo + "）");
						sendMassageInfo(orderId, userTList, 3, 2, 1, sendMessage, -1L);

						// 保存流水信息
						saveOrderFlowFromCRM(orderId, Dictionaries.OrderStatus_04.getIndex(), "CRM指派经销商");

						Map<String, Object> data = new HashMap<>();
						data.put("APPOrderNo", orderNo);
						ParameterTool.writeSuccessResponse(response, data);
					}
				} else {
					String message = "指派经销商不存在，请检查经销商编号是否正确：" + stationNo;
					ParameterTool.writeResponse(response, 1, message);
					saveToAPIExceptionT(interfaceName, message, JsonUtils.toJsonString(requestMap), companyNo);
					return;
				}
			} else if (billStatus.equals("15")) {
				// 修改工单状态
				int orderStatus = 15;
				updateOrderMap.put("OrderStatus", orderStatus);
				crmServiceDao.updateWorkOrderInfo(updateOrderMap);
				saveOrderFlowFromCRM(orderId, orderStatus, "CRM已取消");

				// 给客户发送短信
				String sendUserMessage = String.format("您有工单被取消，工单号%s，请查看。", orderNo);
				String customerPhone = MapUtils.getString(orderInfoMap, "CustomerPhone");
				if (StringUtils.isNotEmpty(customerPhone)) {
					UserT userT = userTDao.getUserByPhone(customerPhone);
					if (null != userT) {
						sendMassageInfo(orderId, userT, 3, 2, 1, sendUserMessage, -1L);
					}
				}

				Long serviceStationId = MapUtils.getLong(orderInfoMap, "ServiceStationId");
				if (NumberUtils.isPositiveNum(serviceStationId)) {
					// 给站长信息员发信息
					List<UserT> userTList = userTDao.getStationMasterListByServiceStationId(serviceStationId);
					String ccssOrderNo = MapUtils.getString(orderInfoMap, "CCSSOrderNo");
					String sendMessage = String.format("您有工单取消，工单号%s，请查看。",
							StringUtils.isBlank(ccssOrderNo) ? orderNo : orderNo + "（FW号" + ccssOrderNo + "）");
					sendMassageInfo(orderId, userTList, 3, 2, 1, sendMessage, -1L);
					// 给技师发信息
					List<UserT> technicians = userTDao.getTechnicianUserListByOrder(orderId,
							Dictionaries.OrderStatus_07.getIndex());
					if (CollectionUtils.isNotEmpty(technicians)) {
						sendMassageInfo(orderId, technicians, 3, 2, 1, sendMessage, -1L);
					}
				}

				Map<String, Object> data = new HashMap<>();
				data.put("APPOrderNo", orderNo);
				ParameterTool.writeSuccessResponse(response, data);
			} else if (billStatus.equals("16")) {
				// 修改工单状态
				int orderStatus = 16;
				updateOrderMap.put("OrderStatus", orderStatus);
				crmServiceDao.updateWorkOrderInfo(updateOrderMap);
				saveOrderFlowFromCRM(orderId, orderStatus, "CRM已关闭");

				Long serviceStationId = MapUtils.getLong(orderInfoMap, "ServiceStationId");
				if (NumberUtils.isPositiveNum(serviceStationId)) {
					// 给站长信息员发信息
					List<UserT> userTList = userTDao.getStationMasterListByServiceStationId(serviceStationId);
					String ccssOrderNo = MapUtils.getString(orderInfoMap, "CCSSOrderNo");
					String sendMessage = String.format("您有工单被关闭，工单号%s，请查看。",
							StringUtils.isBlank(ccssOrderNo) ? orderNo : orderNo + "（FW号" + ccssOrderNo + "）");
					sendMassageInfo(orderId, userTList, 3, 2, 1, sendMessage, -1L);
				}

				Map<String, Object> data = new HashMap<>();
				data.put("APPOrderNo", orderNo);
				ParameterTool.writeSuccessResponse(response, data);
			} else if (billStatus.equals("24")) {
				// 修改工单状态
				int orderStatus = 24;
				updateOrderMap.put("OrderStatus", orderStatus);
				workOrderTDao.updateByPrimaryKeySelective(updateOrderMap);
				saveOrderFlowFromCRM(orderId, orderStatus, "待400审核-400回访/诊断中/继续服务/待更新");

				String ccssOrderNo = MapUtils.getString(orderInfoMap, "CCSSOrderNo");
				String msg = String.format("您有工单待400审核，工单号%s，请尽快处理。",
						StringUtils.isBlank(ccssOrderNo) ? orderNo : orderNo + "（FW号" + ccssOrderNo + "）");
				// 获取工单服务站ID
				Long serviceStationId = MapUtils.getLong(orderInfoMap, "ServiceStationId");
				List<UserT> sendList = null;
				if (NumberUtils.isPositiveNum(serviceStationId)) {
					sendList = positionUserTDao.getUserListByServiceStationIdCompanyId(companyT.getId(),
							serviceStationId);
				} else {
					sendList = positionUserTDao.getUserListByCompanyId(companyT.getId());
				}

				if (CollectionUtils.isNotEmpty(sendList)) {
					//记录下一步处理人
					map.put("ProcessorId", -1L);
					for (UserT principal : sendList) {
						workOrderTService.savePrincipal(orderId, orderStatus, 1, principal.getId(), -1,
								LocalTimeUtil.getRealCurrentTime());
					}
					// 发送相关通知
					sendMassageInfo(orderId, sendList, 3, 2, 1, msg, -1L);
				}

				Map<String, Object> data = new HashMap<>();
				data.put("APPOrderNo", orderNo);
				ParameterTool.writeSuccessResponse(response, data);
			} else if (billStatus.equals("25")) {
				// 修改工单状态
				int orderStatus = 25;
				updateOrderMap.put("OrderStatus", 25);
				crmServiceDao.updateWorkOrderInfo(updateOrderMap);
				saveOrderFlowFromCRM(orderId, orderStatus, "400审核不通过-工单驳回");
				// 根据来源不同发送给不同的人员通知
				String orderSource = MapUtils.getString(orderInfoMap, "OrderSource");
				String sendMessage = String.format("您有工单待更新，工单号%s，请尽快处理。", orderNo);
				if (orderSource.equals("0") || orderSource.equals("2")) {  //2.9.0修复
					// 如果是用户报单或者用户400报修，需要通知用户
					String phone = MapUtils.getString(orderInfoMap, "CustomerPhone");
					UserT userT = userTDao.getUserByPhone(phone);
					if (null != userT) {
						sendMassageInfo(orderId, userT, 3, 2, 1, sendMessage, -1L);
					}
				} else {
					Long serviceStationId = MapUtils.getLong(orderInfoMap, "ServiceStationId");
					// TODO: 2020/3/12 此处如何区分其他来源的工单，比如改派
					List<UserT> userTList = userTDao.getStationMasterListByServiceStationId(serviceStationId);
					sendMassageInfo(orderId, userTList, 3, 2, 1, sendMessage, -1L);
				}
				Map<String, Object> data = new HashMap<>();
				data.put("APPOrderNo", orderNo);
				ParameterTool.writeSuccessResponse(response, data);
			} else if (billStatus.equals("33")) {
				int orderStatus = 33;
				updateOrderMap.put("OrderStatus", 33);
				// TODO: 2020/3/23  该方法需要修改
				crmServiceDao.updateWorkOrderInfo(updateOrderMap);
				saveOrderFlowFromCRM(orderId, orderStatus, "待400主管审核");
				// 保存解决方案
				Map<String, Object> remoteMap = new HashMap<>();
				remoteMap.put("OrderId", orderId);
				remoteMap.put("IsCharged", MapUtils.getString(updateOrderMap, "isClaimant"));
				remoteMap.put("ResolveReason", MapUtils.getString(updateOrderMap, "emoteSolutionType"));
				remoteMap.put("ChargeDescription", MapUtils.getString(updateOrderMap, "claimantDescription"));
				remoteMap.put("Remark", "");
				remoteMap.put("Creator", -1);
				remoteMap.put("CreateTime", LocalTimeUtil.getRealCurrentTime());
				//记录远程解决方案
				orderManageDao.insertResolveRemoteRecord(remoteMap);
				// 发送通知
				List<UserT> userList = orderManageDao.getManagerList();
				if (CollectionUtils.isNotEmpty(userList)) {
					//记录下一步处理人
					map.put("ProcessorId", -1L);
					for (UserT principal : userList) {
						workOrderTService.savePrincipal(orderId, orderStatus, 1, principal.getId(), -1,
								LocalTimeUtil.getRealCurrentTime());
					}

					String ccssOrderNo = MapUtils.getString(orderInfoMap, "CCSSOrderNo");
					String msg = String.format("您有工单待审核，工单号%s，请处理。",
							StringUtils.isBlank(ccssOrderNo) ? orderNo : orderNo + "（FW号" + ccssOrderNo + "）");
					//推送消息
					for (UserT principal : userList) {
						noticeService.push(18, 1, orderId, principal.getId(), principal.getUserName(), "新消息提醒", msg,
								msg, -1L);
						noticeService.sendSMS(18, 1, orderId, principal.getId(), principal.getPhone(), msg, -1L);
					}
				}
				Map<String, Object> data = new HashMap<>();
				data.put("APPOrderNo", orderNo);
				ParameterTool.writeSuccessResponse(response, data);
			} else if (billStatus.equals("34")) {
				int orderStatus = 34;
				updateOrderMap.put("OrderStatus", 34);
				workOrderTDao.updateByPrimaryKeySelective(updateOrderMap);
				saveOrderFlowFromCRM(orderId, orderStatus, "400已取消");

				// 查询工单所属服务商
				Long serviceStationId = MapUtils.getLong(orderInfoMap, "ServiceStationId");
				if (NumberUtils.isPositiveNum(serviceStationId)) {
					// 拼装通知信息
					String ccssOrderNo = MapUtils.getString(orderInfoMap, "CCSSOrderNo");
					String msg = String.format("您有工单取消，工单号%s，请查看。",
							StringUtils.isEmpty(ccssOrderNo) ? orderNo : orderNo + "（FW号" + ccssOrderNo + "）");

					// 给服务商站长/信息员发送通知
					List<UserT> userList = userTDao.getStationMasterListByServiceStationId(serviceStationId);
					if (CollectionUtils.isNotEmpty(userList)) {
						//推送消息
						for (UserT master : userList) {
							noticeService.push(18, 4, orderId, master.getId(), master.getUserName(), "新消息提醒", msg, msg,
									-1L);
							noticeService.sendSMS(18, 4, orderId, master.getId(), master.getPhone(), msg, -1L);
						}
					}
					// 给技师发送通知
					List<UserT> techList = userTDao.getTechnicianUserListByOrder(orderId,
							Dictionaries.OrderStatus_07.getIndex());
					if (CollectionUtils.isNotEmpty(techList)) {
						for (UserT tech : techList) {
							noticeService.push(9, 4, orderId, tech.getId(), tech.getUserName(), "新消息提醒", msg, msg, -1L);
							noticeService.sendSMS(9, 4, orderId, tech.getId(), tech.getPhone(), msg, -1L);
						}
					}
				}
				// 给用户发通知
				String customerPhone = MapUtils.getString(orderInfoMap, "CustomerPhone");
				String message = String.format("您有工单被取消，工单号%s，请查看。", orderNo);
				if (StringUtils.isNotEmpty(customerPhone)) {
					UserT userT = userTDao.getUserByPhone(customerPhone);
					if (null != userT) {
						noticeService.push(9, 4, orderId, userT.getId(), userT.getUserName(), "新消息提醒", message, message,
								-1L);
						noticeService.sendSMS(9, 4, orderId, userT.getId(), userT.getPhone(), message, -1L);
					} else {
						noticeService.sendSMS(9, 4, orderId, null, customerPhone, message, -1L);
					}
				}
				Map<String, Object> data = new HashMap<>();
				data.put("APPOrderNo", orderNo);
				ParameterTool.writeSuccessResponse(response, data);
			} else {
				String message = "非法操作的billStatus：" + billStatus;
				ParameterTool.writeResponse(response, 1, message);
				saveToAPIExceptionT(interfaceName, message, JsonUtils.toJsonString(requestMap), companyNo);
				return;
			}
		}
	}

	private Map<String, Object> convertOrderStatusInfoFromCCEC(CompanyT companyT, Map<String, Object> orderInfoMap,
															   Map<String, Object> requestMap) {
		Map<String, Object> operationMap = new HashMap<>();
		Long orderId = MapUtils.getLong(orderInfoMap, "ID");
		operationMap.put("OrderId", orderId);
		operationMap.put("OrderChannel", companyT.getId());
		operationMap.put("CCSSOrderNo", MapUtils.getString(requestMap, "CCSSOrderNo"));
		operationMap.put("CCSSComplainerOrderNo", MapUtils.getString(requestMap, "CCSSComplainerOrderNo"));
		operationMap.put("billStatus", MapUtils.getString(requestMap, "billStatus"));
		operationMap.put("stationNo", MapUtils.getString(requestMap, "stationNo"));
		operationMap.put("customerName", MapUtils.getString(requestMap, "customerName"));
		operationMap.put("customerPhone", MapUtils.getString(requestMap, "customerPhone"));
		operationMap.put("customerCompany", MapUtils.getString(requestMap, "customerCompany"));
		operationMap.put("isClaimant", MapUtils.getString(requestMap, "isClaimant", "0"));
		operationMap.put("claimantDescription", MapUtils.getString(requestMap, "claimantDescription"));
		operationMap.put("emoteSolutionType", MapUtils.getString(requestMap, "emoteSolutionType"));
		operationMap.put("systemTime", MapUtils.getString(requestMap, "systemTime"));
		operationMap.put("ComplainWorkOrderType", MapUtils.getString(requestMap, "complainOrderType"));
		// 2.4.0新增
		// 故障原因
		operationMap.put("RepairerType", MapUtils.getString(requestMap, "repairerType"));
		operationMap.put("FaultReason", MapUtils.getString(requestMap, "faultReason"));
		return operationMap;
	}

	private void saveOrderFlowFromCRM(Long orderId, Integer orderStatus, String comment) {
		Map<String, Object> saveMap = new HashMap<>();
		saveMap.put("OrderId", orderId);
		saveMap.put("Creator", -1);
		saveMap.put("OrderStatus", orderStatus);
		saveMap.put("CreateTime", LocalTimeUtil.getRealCurrentTime());
		saveWorkOrderFlow(saveMap, comment);
	}

	private void sendMassageInfo(Long orderId, UserT sender, Integer type, Integer function, Integer category,
								 String sendMessage, Long creatorId) {
		List<UserT> senderList = new ArrayList<>();
		senderList.add(sender);
		sendMassageInfo(orderId, senderList, type, function, category, sendMessage, creatorId);
	}

	private void sendMassageInfo(Long orderId, List<UserT> senderList, Integer type, Integer function, Integer category,
								 String sendMessage, Long creatorId) {
		if (type.equals(1) || type.equals(3)) {
			if (CollectionUtils.isNotEmpty(senderList)) {
				for (UserT userT : senderList) {
					noticeService.sendSMS(function, category, orderId, userT.getId(), userT.getPhone(), sendMessage,
							creatorId);
				}
			}
		}
		if (type.equals(2) || type.equals(3)) {
			if (CollectionUtils.isNotEmpty(senderList)) {
				for (UserT userT : senderList) {
					noticeService.push(function, category, orderId, userT.getId(), userT.getUserName(), sendMessage,
							sendMessage, sendMessage, creatorId);
				}
			}
		}
	}

	@Override
	@SuppressWarnings("unchecked")
	public ModelAndView syncQualificationInfo(Map<String, Object> httpMap) {
		HttpServletResponse response = (HttpServletResponse) httpMap.get("response");
		String apiName = "EngineerQualify_T";
		String serviceChannel = MapUtils.getString(httpMap, "company");
		List<Map<String, Object>> crmEngineerQualifyMapList = JSONArray
				.fromObject(httpMap.get(CRMServiceConst.CRM_REQUEST_PARAMS).toString());
		crmLogService.saveCrmErrorLog(serviceChannel, apiName, JsonUtils.toJsonString(crmEngineerQualifyMapList),
				"同步技师资质数据");
		switch (serviceChannel) {
			case "CCI":
				if (CollectionUtils.isNotEmpty(crmEngineerQualifyMapList)) {
					for (Map<String, Object> crmEngineerMap : crmEngineerQualifyMapList) {
						String promotionId = MapUtils.getString(crmEngineerMap, "promotionID");
						if (StringUtils.isEmpty(promotionId)) {
							crmLogService.saveCrmErrorLog(serviceChannel, apiName, JsonUtils.toJsonString(crmEngineerMap),
									"同步技师失败，promotionId为空");
							continue;
						}
						// 先将原有数据删除
						Map<String, Object> deleteMap = new HashMap<>(1);
						deleteMap.put("flag", -1);
						deleteMap.put("promotionId", promotionId);
						engineerQualifyTDao.updateFlagByCondition(deleteMap);

						// 获取技师的SMN列表
						String authorizedModeString = (String) crmEngineerMap.get("authorizedMode");
						if (!StringUtils.isEmpty(authorizedModeString)) {
							List<String> authorizedModeList = Arrays.asList(authorizedModeString.split(";"));
							if (CollectionUtils.isEmpty(authorizedModeList)) {
								crmLogService.saveAppErrorLog(serviceChannel, apiName,
										JsonUtils.toJsonString(crmEngineerMap), "同步技师资质异常，传输SMN信息参数为空");
								continue;
							}

							UserT user = userTDao.getUserByPromotionId(promotionId);
							List<Map<String, Object>> serviceModelNameList = serviceModelNameDao
									.getServiceModelNameList(authorizedModeList);
							if (CollectionUtils.isEmpty(serviceModelNameList)) {
								crmLogService.saveAppErrorLog(serviceChannel, apiName,
										JsonUtils.toJsonString(crmEngineerMap), "同步技师资质异常，本地SMN信息数据为空");
								continue;
							} else {
								if (serviceModelNameList.size() != authorizedModeList.size()) {
									crmLogService.saveAppErrorLog(serviceChannel, apiName,
											JsonUtils.toJsonString(crmEngineerMap), "同步技师资质异常，部分修改，存在未知SMN信息");
								}
								// 拼装SMN表主键ID，通过英文逗号分隔
								StringBuffer sb = new StringBuffer();
								serviceModelNameList.forEach(map -> {
									String idStr = MapUtils.getString(map, "ID");
									if (StringUtils.isNotEmpty(idStr)) {
										sb.append(idStr).append(",");
									}
								});
								String serviceModelNameIds = sb.substring(0, sb.length() - 1);
								Map<String, Object> engineerQualifyMap = new HashMap<>();
								if (null != user) {
									engineerQualifyMap.put("UserPhone", user.getPhone());
									engineerQualifyMap.put("UserName", user.getUserName());
									engineerQualifyMap.put("userId", user.getId());
								}
								engineerQualifyMap.put("promotionId", promotionId);
								engineerQualifyMap.put("serviceModelNameIds", serviceModelNameIds);

								engineerQualifyMap.put("Flag", 0);
								engineerQualifyMap.put("Creator", -1);
								engineerQualifyMap.put("CreateTime", LocalTimeUtil.getRealCurrentTime());
								int saveEngineerQualifyResult = crmServiceDao.insertEngineerQualify_T(engineerQualifyMap);
								if (saveEngineerQualifyResult < 1) {
									crmLogService.saveAppErrorLog(serviceChannel, apiName,
											JsonUtils.toJsonString(crmEngineerMap), "保存技师信息失败");
								}
							}
						}
					}
				} else {
					crmLogService.saveCrmErrorLog(serviceChannel, apiName,
							JsonUtils.toJsonString(crmEngineerQualifyMapList), "同步技师资质数据，技师资质信息列表为空");
				}
				break;
			case "CCEC":
				if (CollectionUtils.isNotEmpty(crmEngineerQualifyMapList)) {
					// 操作过的技师资质信息集合
					Set<String> operationSet = new HashSet<>();
					// 机型信息集合
					Map<String, Long> engineMap = new HashMap<>();
					// 渠道对应企业
					CompanyT companyT = companyTDao.getCompanyInfoByCompanyNo(serviceChannel);
					if (null == companyT) {
						crmLogService.saveCrmErrorLog(serviceChannel, apiName, JsonUtils.toJsonString(httpMap),
								"同步技师资质数据，未知渠道信息");
						ParameterTool.writeResponse(response, 1, "同步技师资质失败，未知渠道信息：" + serviceChannel, new JSONObject());
						return null;
					}

					for (Map<String, Object> crmEngineerMap : crmEngineerQualifyMapList) {
						String requestStatus = MapUtils.getString(crmEngineerMap, "requstStatus");
						String userPhone = MapUtils.getString(crmEngineerMap, "phone");
						if (StringUtils.isEmpty(userPhone)) {
							crmLogService.saveCrmErrorLog(serviceChannel, apiName, JsonUtils.toJsonString(crmEngineerMap),
									"同步技师失败，phone为空");
							continue;
						}

						// 获取技师的授权机型列表
						String engineTypeStr = MapUtils.getString(crmEngineerMap, "engineType");
						if (!StringUtils.isEmpty(engineTypeStr)) {
							List<String> engineTypeList = Arrays.asList(engineTypeStr.split(","));
							if (CollectionUtils.isEmpty(engineTypeList)) {
								crmLogService.saveAppErrorLog(serviceChannel, apiName,
										JsonUtils.toJsonString(crmEngineerMap), "同步技师资质异常，传输机型信息参数为空");
								continue;
							}
							UserT user = userTDao.getUserByPhone(userPhone);
							for (String engineTypeName : engineTypeList) {
								if ("2".equals(requestStatus)) {
									Map<String, Object> deleteMap = new HashMap<>(1);
									deleteMap.put("deleter", companyT.getId());
									deleteMap.put("deleteTime", LocalTimeUtil.getRealCurrentTime());
									deleteMap.put("userPhone", userPhone);
									deleteMap.put("engineTypeName", engineTypeName);
									engineerQualifyTDao.deleteByPhoneAndTypeName(deleteMap);
									continue;
								} else {
									// 判断该用户，该资质是否处理过，处理过则跳过
									String operationInfo = userPhone + engineTypeName;
									if (operationSet.contains(operationInfo)) {
										crmLogService.saveAppErrorLog(serviceChannel, apiName,
												JsonUtils.toJsonString(crmEngineerMap), "同步技师资质异常，传输机型信息参数为空");
										continue;
									} else {
										operationSet.add(operationInfo);
									}
									// 获取机型ID
									Long engineTypeId = null;
									if (engineMap.containsKey(engineTypeName)) {
										engineTypeId = engineMap.get(engineTypeName);
									} else {
										EngineTypeT engineTypeT = engineTypeTDao.getEngineTypeByTypeName(engineTypeName);
										if (null != engineTypeT) {
											engineTypeId = engineTypeT.getId();
											engineMap.put(engineTypeName, engineTypeId);
										}
									}

									// 新增or修改资质数据
									int saveEngineerQualifyResult = 0;
									// 获取数据库资质数据
									Map<String, Object> dataEngineerQualifyMap = engineerQualifyTDao
											.selectByPhoneAndTypeName(userPhone, engineTypeName);
									if (MapUtils.isEmpty(dataEngineerQualifyMap)) {
										// 不存在对应资质，新增
										Map<String, Object> engineerQualifyMap = new HashMap<>();
										engineerQualifyMap.put("UserPhone", userPhone);
										if (null != user) {
											engineerQualifyMap.put("UserName", user.getUserName());
											engineerQualifyMap.put("userId", user.getId());
										}
										engineerQualifyMap.put("EngineTypeId", engineTypeId);
										engineerQualifyMap.put("EngineTypeName", engineTypeName);
										engineerQualifyMap.put("idNumber", MapUtils.getString(crmEngineerMap, "IDNumber"));
										engineerQualifyMap.put("Flag", 0);
										engineerQualifyMap.put("Creator", companyT.getId());
										engineerQualifyMap.put("CreateTime", LocalTimeUtil.getRealCurrentTime());
										saveEngineerQualifyResult = crmServiceDao
												.insertEngineerQualify_T(engineerQualifyMap);
									} else {
										// 存在对应资质，更新
										dataEngineerQualifyMap.put("id", MapUtils.getLong(dataEngineerQualifyMap, "ID"));
										dataEngineerQualifyMap.put("idNumber",
												MapUtils.getString(crmEngineerMap, "IDNumber"));
										if (null != user) {
											dataEngineerQualifyMap.put("username", user.getUserName());
											dataEngineerQualifyMap.put("userId", user.getId());
										}
										dataEngineerQualifyMap.put("updator", companyT.getId());
										dataEngineerQualifyMap.put("updateTime", LocalTimeUtil.getRealCurrentTime());
										engineerQualifyTDao.updateByPrimaryKeySelective(dataEngineerQualifyMap);
									}
									if (saveEngineerQualifyResult < 1) {
										crmLogService.saveAppErrorLog(serviceChannel, apiName,
												JsonUtils.toJsonString(crmEngineerMap), "保存技师信息失败");
									}
								}
							}
						} else {
							crmLogService.saveAppErrorLog(serviceChannel, apiName, JsonUtils.toJsonString(crmEngineerMap),
									"同步技师资质异常，传输机型信息参数为空");
							continue;
						}
					}
				} else {
					crmLogService.saveCrmErrorLog(serviceChannel, apiName,
							JsonUtils.toJsonString(crmEngineerQualifyMapList), "同步技师资质数据，技师资质信息列表为空");
					ParameterTool.writeResponse(response, 1, "同步技师资质失败，技师资质信息列表为空：" + serviceChannel, new JSONObject());
					return null;
				}
				break;
			default:
				ParameterTool.writeResponse(response, 1, "未知渠道信息：" + serviceChannel, new JSONObject());
				return null;
		}
		ParameterTool.writeResponse(response, 0, "服务技师资质同步成功", new JSONObject());
		return null;
	}

	/**
	 * @return org.springframework.web.servlet.ModelAndView
	 * @Author Joe
	 * @Description 更新发动机信息
	 * @Date 4:06 PM 2019/7/26
	 * @Param [httpMap]
	 **/
	@Override
	public ModelAndView updateEngineInfo(Map<String, Object> httpMap) {
		HttpServletRequest request = (HttpServletRequest) httpMap.get("request");
		HttpServletResponse response = (HttpServletResponse) httpMap.get("response");

		String company = httpMap.get(CRMServiceConst.CRM_REQUEST_COMPANY).toString();// 渠道
		JSONObject jsonObject = new JSONObject(); // 返回定义
		int updateResult = -1;
		if (company.equals(CRMServiceConst.DBU)) {

			@SuppressWarnings("unchecked")
			Map<String, Object> requestMap = (Map<String, Object>) JSONObject
					.fromObject(httpMap.get(CRMServiceConst.CRM_REQUEST_PARAMS).toString());

			// 更新发动机基础信息表
			if (requestMap.containsKey("ESN") && requestMap.get("ESN").toString().length() > 0) {
				Map<String, Object> engineMsgParamMap = new HashMap<>();
				engineMsgParamMap.put("ESN", MapUtils.getString(requestMap, "ESN", ""));
				engineMsgParamMap.put("serviceChannel", company);
				Map<String, Object> engineMsgMap = crmServiceDao.getEngineMsgByESNAndChannel(engineMsgParamMap);
				engineMsgMap.put("equipmentNo", MapUtils.getString(requestMap, "equipmentNo", ""));
				engineMsgMap.put("vehicleCompany", MapUtils.getString(requestMap, "vehicleCompany", ""));
				engineMsgMap.put("engineType", MapUtils.getString(requestMap, "engineType", ""));
				engineMsgMap.put("manufactor", MapUtils.getString(requestMap, "manufactor", ""));
				engineMsgMap.put("serviceChannel", MapUtils.getString(requestMap, "serviceChannel", ""));
				engineMsgMap.put("saleDate", MapUtils.getString(requestMap, "saleDate", ""));
				engineMsgMap.put("SMN", MapUtils.getString(requestMap, "SMN", ""));
				engineMsgMap.put("MarketType", MapUtils.getString(requestMap, "marketTypes", ""));
				engineMsgMap.put("Application", MapUtils.getString(requestMap, "applications", ""));
				engineMsgMap.put("WarrantyStartDate", MapUtils.getString(requestMap, "warrantyStartDate", ""));
				updateResult = engineMsgDao.updateEngineMsg(engineMsgMap);
				if (updateResult > 0) {
					LOG.info("发动机信息更新成功");
					jsonObject.put("status", 0);
					jsonObject.put("msg", "发动机信息更新成功");
					jsonObject.put("data", new JSONObject());
					ParameterTool.writeResponse(response, jsonObject.toString());
				} else {
					LOG.info("发动机信息更新失败");
					jsonObject.put("status", 1);
					jsonObject.put("msg", "发动机信息更新失败");
					jsonObject.put("data", new JSONObject());
					ParameterTool.writeResponse(response, jsonObject.toString());
				}
			}
		}
		return null;
	}

	@Override
	public ModelAndView syncAllServiceStationsLatAndLon(Map<String, Object> map) {
		HttpServletResponse response = (HttpServletResponse) map.get("response");
		JSONObject obj = new JSONObject();
		List<Map<String, Object>> serviceStationList = new ArrayList<>();
		if (map.containsKey("serviceChannel")) {
			if (MapUtils.getString(map, "serviceChannel", "").equals("XCEC")
					|| MapUtils.getString(map, "serviceChannel", "").equals("CCI")) {

				serviceStationList = crmServiceDao.getAllServiceStationByCompanyNo(map);

			} else if (MapUtils.getString(map, "serviceChannel", "").equals("XCEC")) {
				serviceStationList = crmServiceDao.getDCECAllServiceStationByCompanyNo(map);
			} else {
				obj.put("status", 1);
				obj.put("msg", "渠道输入不正确");
				obj.put("data", new JSONObject());
				ParameterTool.writeResponse(response, obj.toString());
				return null;
			}

			if (CollectionUtils.isNotEmpty(serviceStationList)) {
				/**
				 * 如果经纬度有更新需要同步给CRM系统
				 */
				try {
					CRMResponeEntity responeEntity = CRMApiUtils.getCRMServiceApi().updateServiceStationLonAndLatInfos(
							map.get("serviceChannel").toString(), serviceStationList);
					if (responeEntity.getStatus() == 0) {
						obj.put("status", 0);
						obj.put("msg", "服务商经纬度同步成功");
						obj.put("data", new JSONObject());
						ParameterTool.writeResponse(response, obj.toString());
					} else {
						obj.put("status", 1);
						obj.put("msg", "服务商经纬度同步失败");
						obj.put("data", new JSONObject());
						ParameterTool.writeResponse(response, obj.toString());
					}
				} catch (Exception e) {
					LOG.error(e.getMessage(), e);
				}
			} else {
				obj.put("status", 1);
				obj.put("msg", "渠道输入不正确");
				obj.put("data", new JSONObject());
				ParameterTool.writeResponse(response, obj.toString());
			}

		} else {
			obj.put("status", 1);
			obj.put("msg", "渠道输入不正确");
			obj.put("data", new JSONObject());
			ParameterTool.writeResponse(response, obj.toString());
		}
		return null;

	}

	@Override
	@SuppressWarnings("unchecked")
	public void syncErrorPictures(Map<String, Object> map) {
		HttpServletResponse response = (HttpServletResponse) map.get("response");

		String company = MapUtils.getString(map, CRMServiceConst.CRM_REQUEST_COMPANY, "");// 渠道
		if (!"CCI".equals(company)) {
			ParameterTool.writeResponse(response, 1, "未知渠道信息:" + company);
			return;
		}

		String params = MapUtils.getString(map, CRMServiceConst.CRM_REQUEST_PARAMS);
		if (StringUtils.isNotEmpty(params)) {
			Map<String, Object> requestMap = (Map<String, Object>) JSONObject.fromObject(params);
			String orderNo = MapUtils.getString(requestMap, "orderNo");
			Map<String, Object> orderMap = workOrderTDao.getOrderByNo(orderNo);
			if (MapUtils.isEmpty(orderMap)) {
				ParameterTool.writeResponse(response, 1, "未知工单编号:" + orderNo);
				return;
			}
			Long orderId = MapUtils.getLong(orderMap, "ID");
			// 获取到原照片列表
			List<WorkOrderPics> shootingPictureList = workOrderPicsDao.getWorkOrderPictureListByOrderId(orderId);
			// 将原列表搞成map，存ID
			Map<String, Long> shootingIdMap = new HashMap<>();
			if (CollectionUtils.isNotEmpty(shootingPictureList)) {
				for (WorkOrderPics workOrderPics : shootingPictureList) {
					String picNo = workOrderPics.getPicNo();
					Long shootingId = workOrderPics.getId();
					shootingIdMap.put(picNo, shootingId);
				}
			}
			// 解析错误照片列表
			List<Map<String, Object>> paramMapList = (List<Map<String, Object>>) MapUtils.getObject(requestMap,
					"pictureList");
			if (CollectionUtils.isNotEmpty(paramMapList)) {
				String currentDate = LocalTimeUtil.getRealCurrentTime();
				for (Map<String, Object> paramMap : paramMapList) {
					// TODO: 2020/2/18 多次补拍
					String pictureLocation = MapUtils.getString(paramMap, "picLocation");
					String description = MapUtils.getString(paramMap, "description");
					String comments = MapUtils.getString(paramMap, "comments");
					WorkOrderRemedyPicture lastRemedyPicture = workOrderRemedyPictureDao
							.selectLastByOrderIdAndPicNo(orderId, pictureLocation);
					if (null == lastRemedyPicture) {
						WorkOrderRemedyPicture remedyPicture = new WorkOrderRemedyPicture();
						remedyPicture.setOrderId(orderId);
						remedyPicture.setOriginalId(shootingIdMap.get(pictureLocation));
						remedyPicture.setPictureLocation(pictureLocation);
						remedyPicture.setDescription(description);
						remedyPicture.setComments(comments);
						remedyPicture.setCreator(1L);
						remedyPicture.setCreateTime(currentDate);
						workOrderRemedyPictureDao.insertSelective(remedyPicture);
					} else {
						// 大于0次说明已经补拍过
						if (NumberUtils.isPositiveNum(lastRemedyPicture.getRemedyCount())) {
							WorkOrderRemedyPicture remedyPicture = new WorkOrderRemedyPicture();
							remedyPicture.setOrderId(orderId);
							remedyPicture.setOriginalId(shootingIdMap.get(pictureLocation));
							remedyPicture.setPictureLocation(pictureLocation);
							remedyPicture.setDescription(description);
							remedyPicture.setComments(comments);
							remedyPicture.setCreator(1L);
							remedyPicture.setCreateTime(currentDate);
							workOrderRemedyPictureDao.insertSelective(remedyPicture);
						} else {
							lastRemedyPicture.setDescription(description);
							lastRemedyPicture.setComments(comments);
							lastRemedyPicture.setUpdator(1L);
							lastRemedyPicture.setUpdateTime(currentDate);
							workOrderRemedyPictureDao.updateByPrimaryKeySelective(lastRemedyPicture);
						}
					}
				}
			}
			// TODO: 2020/2/18 通知技师等补拍
			Map<String, Object> technicianMap = userTDao.getUserByOrderId(orderId);
			if (MapUtils.isNotEmpty(technicianMap)) {
				String sendMsg = "您有工单照片存在问题，请及时进行补拍，工单编号：" + orderNo;
				Long technicianId = MapUtils.getLong(technicianMap, "ID");
				String username = MapUtils.getString(technicianMap, "UserName");
				String phone = MapUtils.getString(technicianMap, "Phone");
				noticeService.push(17, 6, orderId, technicianId, username, "工单照片异常提醒", sendMsg, sendMsg, 1L);
				noticeService.sendSMS(17, 6, orderId, technicianId, phone, sendMsg, 1L);
			}
			ParameterTool.writeSuccessResponse(response);
		}
	}

	/**
	 * @Description 根据诊断工单编号获取详情
	 **/
	@Override
	public ModelAndView getDiagnosticMsgByDROrderNo(Map<String, Object> httpMap) {
		HttpServletRequest request = (HttpServletRequest) httpMap.get("request");
		HttpServletResponse response = (HttpServletResponse) httpMap.get("response");

		//String company = httpMap.get(CRMServiceConst.CRM_REQUEST_COMPANY).toString();// 渠道
		JSONObject jsonObject = new JSONObject(); // 返回定义
		int updateResult = -1;
		@SuppressWarnings("unchecked")
		Map<String, Object> requestMap = (Map<String, Object>) JSONObject
				.fromObject(httpMap.get(CRMServiceConst.CRM_REQUEST_PARAMS).toString());
		String drOrderNo = MapUtils.getString(requestMap, "drOrderNo", "");
		if (StringUtils.isEmpty(drOrderNo)) {
			jsonObject.put("status", 1);
			jsonObject.put("msg", "诊断工单编号不能为空");
			jsonObject.put("data", new JSONObject());
			ParameterTool.writeResponse(response, jsonObject.toString());
			return null;
		}
		Map<String, Object> drWorkOrderMap = workOrderDrDao.getDRWorkOrderByOrderNo(drOrderNo);
		if (MapUtils.isEmpty(drWorkOrderMap)) {
			jsonObject.put("status", 1);
			jsonObject.put("msg", "未查询到诊断工单");
			jsonObject.put("data", new JSONObject());
			ParameterTool.writeResponse(response, jsonObject.toString());
			return null;
		} else {
			int drWorkOrderStatus = MapUtils.getIntValue(drWorkOrderMap, "Status"); //诊断工单状态  0未完成    1已完成
			if (drWorkOrderStatus != 1) {
				jsonObject.put("status", 1);
				jsonObject.put("msg", "诊断工单尚未完成，不能下载pdf");
				jsonObject.put("data", new JSONObject());
				ParameterTool.writeResponse(response, jsonObject.toString());
				return null;
			}
			long drWorkOrderId = MapUtils.getLongValue(drWorkOrderMap, "ID");
			//获取配置文件中调用system项目中通过诊断工单id下载pdf接口    并返回pdf在服务器的地址
			String drPdfDiagnoseReportUrl = PropertiesUtil.getProperties("projectconfig.properties",
					"drPdfDiagnoseReport") + drWorkOrderId;
			String responseStr = HttpUtils.get(drPdfDiagnoseReportUrl, new ResponseHandler<String>() {
				@Override
				public String handleResponse(HttpResponse response) throws ClientProtocolException, IOException {
					if (response.getStatusLine().getStatusCode() == 200) {
						HttpEntity httpEntity = response.getEntity();
						return EntityUtils.toString(httpEntity);
					} else {
						LOG.error("异常，response：" + response);
					}
					return null;
				}
			});
			Map<String, Object> responseStrMap = JsonUtils.toJavaObject(responseStr, Map.class);
			if (MapUtils.isEmpty(responseStrMap)) {
				jsonObject.put("status", 1);
				jsonObject.put("msg", "生成pdf文件失败");
				jsonObject.put("data", new JSONObject());
				ParameterTool.writeResponse(response, jsonObject.toString());
				return null;
			} else {
				Map<String, Object> data = (Map<String, Object>) responseStrMap.get("data");
				String pdfUrl = MapUtils.getString(data, "url", "");
				String secretKey = MapUtils.getString(drWorkOrderMap, "SecretKey");
				if (StringUtils.isEmpty(secretKey)) {
					secretKey = drOrderNo;
				}
				LOG.info("诊断工单密钥：" + secretKey);
				//获取配置文件中调用system项目中通过诊断工单编号打开web端打开诊断工单详情页面的url
				String drDiagnoseReportUrl = PropertiesUtil.getProperties("projectconfig.properties",
						"drDiagnoseReport") + secretKey;
				List<Map<String, Object>> doneSolutionIDList = workOrderDrDao
						.getDoneSolutionIDListByOrderId(drWorkOrderId);
				String doneSolutionIDStr = ""; //拼接执行过的方案编号 以英文逗号隔开
				if (CollectionUtils.isNotEmpty(doneSolutionIDList)) {
					for (Map<String, Object> doneSolutionID : doneSolutionIDList) {
						doneSolutionIDStr += MapUtils.getString(doneSolutionID, "SolutionID") + ",";
					}
					if (doneSolutionIDStr.endsWith(",")) {
						doneSolutionIDStr = doneSolutionIDStr.substring(0, doneSolutionIDStr.length() - 1);
					}
				}
				JSONObject workOrderInfo = new JSONObject();
				workOrderInfo.put("DoneSolutionNo", doneSolutionIDStr);
				workOrderInfo.put("PdfAddress", pdfUrl);
				workOrderInfo.put("WebAddress", drDiagnoseReportUrl);
				workOrderInfo.put("ESN", MapUtils.getString(drWorkOrderMap, "ESN"));
				workOrderInfo.put("SMN", MapUtils.getString(drWorkOrderMap, "SMN"));
				LOG.info("crm通过诊断工单编号获取诊断工单信息成功");
				jsonObject.put("status", 0);
				jsonObject.put("msg", "success");
				jsonObject.put("data", workOrderInfo);
				ParameterTool.writeResponse(response, jsonObject.toString());
			}
		}
		return null;
	}

	/**
	 * 根据ESN获取SMN
	 *
	 * @param map
	 * @return
	 */
	@Override
	public ModelAndView getSMNByESN(Map<String, Object> map) {
		HttpServletResponse response = (HttpServletResponse) map.get("response");
		HttpServletRequest request = (HttpServletRequest) map.get("request");
		@SuppressWarnings("unchecked")
		Map<String, Object> requestMap = (Map<String, Object>) JSONObject
				.fromObject(map.get(CRMServiceConst.CRM_REQUEST_PARAMS).toString());
		//1. 定义返回结果
		JSONObject obj = new JSONObject();
		JSONObject obj_data = new JSONObject();
		String ESN = MapUtils.getString(requestMap, "ESN");
		//2. 获取ESN
		if (StringUtils.isNotEmpty(ESN)) {
			int isValidate = 0; //初始化验证信息，0为需新增内容，1为需更新内容
			//2.1 调用common接口
			EngineMsg esn_Result = engineMsgDao.getEngineMsgByESNString(ESN);
			if (null != esn_Result) {
				if (StringUtils.isNotEmpty(esn_Result.getSMN()) && !"DUMMY".equals(esn_Result.getSMN())) {
					// 本地获取到SMN
					LOG.info("crm通过诊断工单编号获取诊断工单信息成功");
					obj_data.put("SMN", esn_Result.getSMN());
					obj.put("status", 0);
					obj.put("msg", "success");
					obj.put("data", obj_data);
					ParameterTool.writeResponse(response, obj.toString());
					return null;
				}
				isValidate = 1; //本地查找到esn_Result，但是SMN为空，或者为DUMMY，需进行本地更新
			}
			//2.2 调用晓闪Siebel API

			//			Header token = new BasicHeader("Authorization",request.getHeader("token"));
			String url = PropertiesUtil.getProperties("projectconfig.properties", "getSMNByESNFromSIEBELUrl");
			url = String.format(url, ESN).trim();
			String response_eCummins = HttpUtils.get(url, new ResponseHandler<String>() {
				@Override
				public String handleResponse(HttpResponse response) throws ClientProtocolException, IOException {
					if (response.getStatusLine().getStatusCode() == 200) {
						HttpEntity httpEntity = response.getEntity();
						LOG.info("调用Common接口成功，response：" + response);
						return EntityUtils.toString(httpEntity);
					} else {
						LOG.error("异常，response：" + response);
					}
					return null;
				}
			}, null, null);
			Map<String, Object> enginerMsg = JsonUtils.toJavaObject(response_eCummins, Map.class);
			if (MapUtils.getInteger(enginerMsg, "status") == 0) {
				//若查询到相关内容后： 1. isValidate =1，则需要进行本地更新；2. isValidate = 0,则需要进行本地新增
				Map<String, Object> data = (Map<String, Object>) MapUtils.getMap(enginerMsg, "data");
				String SMN = MapUtils.getString(data, "SMN");
				Map<String, Object> paramsMap = new HashMap<>();
				if (isValidate == 1) {
					paramsMap.put("SMN", SMN);
					paramsMap.put("id", esn_Result.getId());
					engineMsgDao.updateEngineMsg(paramsMap);
				}
				if (isValidate == 0) {
					paramsMap.put("SMN", SMN);
					paramsMap.put("ESN", ESN);
					engineMsgDao.insertEngineMsg(paramsMap);
				}
				obj.put("status", 0);
				obj.put("msg", "success");
				obj.put("data", data);
				ParameterTool.writeResponse(response, obj.toString());
				return null;
			}
			obj.put("status", 1);
			obj.put("msg", MapUtils.getString(enginerMsg, "msg"));
			obj.put("data", "");
			ParameterTool.writeResponse(response, obj.toString());
			return null;
		} else {
			LOG.info("ESN为空");
			obj.put("status", 1);
			obj.put("msg", "ESN为空");
			obj.put("data", new JSONObject());
			ParameterTool.writeResponse(response, obj.toString());
		}
		return null;
	}

	@Override
	@Transactional
	public ModelAndView syncPartInfos(Map<String, Object> map) {
		HttpServletResponse response = (HttpServletResponse) map.get("response");
		String company = MapUtils.getString(map, "company");
		if (StringUtils.isNotEmpty(company)) {
			String paramJson = MapUtils.getString(map, CRMServiceConst.CRM_REQUEST_PARAMS);
			if (StringUtils.isNotEmpty(paramJson)) {
				List<PartInfoT> partInfoTList = JsonUtils.convertJsonArrayToList(paramJson, PartInfoT.class);
				if (CollectionUtils.isNotEmpty(partInfoTList)) {
					for (PartInfoT partInfoT : partInfoTList) {
						partInfoT.setCreateTime(LocalTimeUtil.getRealCurrentTime());
					}
					// 分批次入库
					Integer size = partInfoTList.size();
					Integer startIndex = 0;
					Integer endIndex = 0;
					while (endIndex < size) {
						endIndex = startIndex + BATCH_LIMIT > size ? size : startIndex + BATCH_LIMIT;
						List<PartInfoT> subPartInfoList = partInfoTList.subList(startIndex, endIndex);
						partInfoTDao.batchInsert(subPartInfoList);
						startIndex = endIndex;
					}
					ParameterTool.writeSuccessResponse(response);
				} else {
					ParameterTool.writeResponse(response, 1, "零件列表为空");
				}
			} else {
				ParameterTool.writeResponse(response, 1, "Param参数信息为空");
			}
		}
		return null;
	}

	@Override
	public ModelAndView syncEngineInfos(Map<String, Object> map) {
		HttpServletResponse response = (HttpServletResponse) map.get("response");
		// String company = MapUtils.getString(map,CRMServiceConst.CRM_REQUEST_COMPANY);
		// 获取参数列表字符串
		String paramJson = MapUtils.getString(map, CRMServiceConst.CRM_REQUEST_PARAMS);
		if (StringUtils.isNotEmpty(paramJson)) {
			// 转换为参数列表
			List<Map<String, Object>> originEngineMapList = JSONArray.fromObject(paramJson);
			if (CollectionUtils.isNotEmpty(originEngineMapList)) {
				// 操作的ESN集合，为了过滤一次请求中相同ESN
				Set<String> operationSet = new HashSet<>();
				List<Map<String, Object>> insertMapList = new ArrayList<>();
				List<Map<String, Object>> updateMapList = new ArrayList<>();
				for (Map<String, Object> originEngineMap : originEngineMapList) {
					String esn = MapUtils.getString(originEngineMap, "ESN");
					// 判断该ESN在该次请求中是否已经处理过
					if (operationSet.contains(esn)) {
						continue;
					} else {
						operationSet.add(esn);
					}
					EngineMsg dataEngineMsg = engineMsgDao.getEngineMsgByESNString(esn);
					if (null != dataEngineMsg) {
						Map<String, Object> convertMap = convertEngineMap(dataEngineMsg, originEngineMap);
						convertMap.put("updateTime", LocalTimeUtil.getRealCurrentTime());
						updateMapList.add(convertMap);
					} else {
						Map<String, Object> convertMap = convertEngineMap(null, originEngineMap);
						convertMap.put("createTime", LocalTimeUtil.getRealCurrentTime());
						insertMapList.add(convertMap);
					}
				}
				if (CollectionUtils.isNotEmpty(updateMapList)) {
					batchUpdateEngineMsg(updateMapList);
				}
				if (CollectionUtils.isNotEmpty(insertMapList)) {
					batchInsertEngineMsg(insertMapList);
				}
				ParameterTool.writeSuccessResponse(response);
			} else {
				ParameterTool.writeResponse(response, 1, "同步参数列表数据为空。");
			}
		} else {
			ParameterTool.writeResponse(response, 1, "同步参数列表数据为空。");
		}
		return null;
	}

	private Map<String, Object> convertEngineMap(EngineMsg srcEngineMsg, Map<String, Object> originEngineMap) {
		Map<String, Object> convertMap = new HashMap<>();
		String esn = MapUtils.getString(originEngineMap, "ESN");
		convertMap.put("ESN", MapUtils.getString(originEngineMap, "ESN"));
		convertMap.put("SMN", MapUtils.getString(originEngineMap, "SMN"));
		convertMap.put("equipmentNo", MapUtils.getString(originEngineMap, "equipmentNo"));
		convertMap.put("vehicleCompany", MapUtils.getString(originEngineMap, "vehicleCompany"));
		convertMap.put("engineType", MapUtils.getString(originEngineMap, "engineType"));
		convertMap.put("manufactor", MapUtils.getString(originEngineMap, "manufactor"));
		convertMap.put("serviceChannel", MapUtils.getString(originEngineMap, "serviceChannel"));
		convertMap.put("marketType", MapUtils.getString(originEngineMap, "marketTypes"));
		convertMap.put("application", MapUtils.getString(originEngineMap, "applications"));
		String warrantyStartDate = MapUtils.getString(originEngineMap, "warrantyStartDate");
		convertMap.put("warrantyStartDate", warrantyStartDate);
		if (StringUtils.isNotEmpty(warrantyStartDate)) {
			warrantyStartDate = warrantyStartDate + " 00:00:00";
			if (LocalTimeUtil.isBefore(warrantyStartDate, LocalTimeUtil.getRealCurrentTime())) {
				convertMap.put("isWarrantyStart", 1);
			} else {
				convertMap.put("isWarrantyStart", 0);
			}
		} else {
			convertMap.put("isWarrantyStart", 0);
		}
		convertMap.put("estimateWarrantyStartDate", MapUtils.getString(originEngineMap, "estimateWarrantyStartDate"));
		convertMap.put("series", MapUtils.getString(originEngineMap, "series"));
		convertMap.put("buBusinessUnit", MapUtils.getString(originEngineMap, "BUBusinessUnit"));
		convertMap.put("engineProducedDate", MapUtils.getString(originEngineMap, "engineStartDate"));
		convertMap.put("soNo", MapUtils.getString(originEngineMap, "SONumber"));
		convertMap.put("engineStartDatePicUrl", MapUtils.getString(originEngineMap, "engineStartDatePicUrl"));

		if (null != srcEngineMsg) {
			convertMap.put("id", srcEngineMsg.getId());
		}
		return convertMap;
	}

	private void batchUpdateEngineMsg(List<Map<String, Object>> list) {
		Integer size = list.size();
		Integer startIndex = 0;
		Integer endIndex = 0;
		while (endIndex < size) {
			endIndex = startIndex + BATCH_LIMIT > size ? size : startIndex + BATCH_LIMIT;
			List<Map<String, Object>> subList = list.subList(startIndex, endIndex);
			engineMsgDao.updateBatchByPrimaryKeySelective(subList);
			startIndex = endIndex;
		}
	}

	private void batchInsertEngineMsg(List<Map<String, Object>> list) {
		Integer size = list.size();
		Integer startIndex = 0;
		Integer endIndex = 0;
		while (endIndex < size) {
			endIndex = startIndex + BATCH_LIMIT > size ? size : startIndex + BATCH_LIMIT;
			List<Map<String, Object>> subList = list.subList(startIndex, endIndex);
			engineMsgDao.insertBatchSelective(subList);
			startIndex = endIndex;
		}
	}

	// ++++++++++++++++++++++++++++++++++++++++工具方法++++++++++++++++++++++++++++++++++++++++++++++++++//
	public JSONObject crmCreatWorkOrderByDBU(Map<String, Object> orderMap) {
		/**
		 * 1、定义返回结果
		 */
		JSONObject obj = new JSONObject();
		/**
		 * 2、根据电话号码获取APP系统的userid
		 */
		String customerPhone = orderMap.get("CustomerPhone").toString();
		List<UserT> users = loginDao.getUserByPhone(customerPhone);
		if (users != null && users.size() > 0) {
			long lCustomerId = users.get(0).getId();
			orderMap.put("CustomerId", lCustomerId);
		}
		/**
		 * 3、根据CompanyNo获取对应的Company信息
		 */
		CompanyT company = companyTDao.getCompanyInfoByCompanyNo(orderMap.get("CompanyNo").toString());
		if (company == null) {
			LOG.info("服务渠道没有查询到\n" + JsonUtils.toJsonString(orderMap));
			obj.put("status", 1);
			obj.put("msg", "服务渠道未查询到");
			obj.put("data", new JSONObject());
			return obj;
		}
		orderMap.put("OrderChannel", company.getId());
		orderMap.put("OrderChannelName", company.getCompanyNo());
		/**
		 * 4、根据ESN获取对应的EngineMsgId、OEMName 4.1先根据发动机号ESN从发动机信息表EngineMsg中查询是否有数据
		 */
		EngineMsg engineMsg = engineMsgDao.getEngineMsgByESN(orderMap);
		EngineMsg engineMsgByAmt = engineMsgDao.getEngineMsgByAmtNo(orderMap);
		if (engineMsg != null) { // 如果发动机信息表EngineMsg中查询到数据
			orderMap.put("EngineMsgId", engineMsg.getId());
			if (orderMap.get("OEMName").toString().length() < 1) {
				orderMap.put("OEMName", (engineMsg.getVehicleCompany() == null) ? "" : engineMsg.getVehicleCompany());
			}
		}

		/**
		 * 如果通过esn 拿不到数据
		 * 通过amtNo去获取数据
		 */
		else if ( engineMsg == null  && engineMsgByAmt != null) {
			orderMap.put("EngineMsgId", engineMsgByAmt.getId());
			if (orderMap.get("OEMName").toString().length() < 1) {
				orderMap.put("OEMName", (engineMsgByAmt.getVehicleCompany() == null) ? "" : engineMsgByAmt.getVehicleCompany());
			}
		}
		else {
			// 发动机信息表EngineMsg中没有查询到数据，就根据发动机号(ESN)和服务渠道serviceChannel调用CRM接口查询发动机数据
			CRMResponeEntity cRMResponeEntity = CRMApiUtils.getCRMServiceApi().verifyEngineInfo(company.getCompanyNo(),
					orderMap.get("ESN").toString());
			if (cRMResponeEntity.getStatus() == 0) {
				// 保存发动机信息表
				if (cRMResponeEntity.getData() != null && !cRMResponeEntity.getData().isEmpty()) {
					Map<String, Object> engineMsgMap = new HashedMap<String, Object>();
					engineMsgMap.put("ESN", orderMap.get("ESN"));
					engineMsgMap.put("SMN", cRMResponeEntity.getData().get("SMN"));
					engineMsgMap.put("equipmentNo", cRMResponeEntity.getData().get("equipmentNo"));
					engineMsgMap.put("vehicleCompany", cRMResponeEntity.getData().get("vehicleCompany"));
					engineMsgMap.put("engineType", cRMResponeEntity.getData().get("engineType"));
					engineMsgMap.put("manufactor", cRMResponeEntity.getData().get("manufactor"));
					engineMsgMap.put("serviceChannel", cRMResponeEntity.getData().get("serviceChannel"));
					engineMsgMap.put("saleDate", cRMResponeEntity.getData().get("saleDate"));
					engineMsgMap.put("MarketType", cRMResponeEntity.getData().get("marketTypes"));
					engineMsgMap.put("Application", cRMResponeEntity.getData().get("applications"));
					engineMsgMap.put("WarrantyStartDate", cRMResponeEntity.getData().get("warrantyStartDate"));

					engineMsgDao.insertEngineMsg(engineMsgMap); // 保存

					orderMap.put("EngineMsgId", engineMsgMap.get("id"));
					orderMap.put("OEMName", cRMResponeEntity.getData().get("vehicleCompany"));
				} else {
					Map<String, Object> engineMsgMap = new HashedMap<String, Object>();
					engineMsgMap.put("ESN", orderMap.get("ESN"));
					engineMsgMap.put("SMN", "");
					engineMsgMap.put("equipmentNo", "");
					engineMsgMap.put("vehicleCompany", orderMap.get("OEMName"));
					engineMsgMap.put("engineType", "");
					engineMsgMap.put("manufactor", "");
					engineMsgMap.put("serviceChannel", "");
					engineMsgMap.put("saleDate", "");
					engineMsgMap.put("MarketType", "");
					engineMsgMap.put("Application", "");
					engineMsgMap.put("WarrantyStartDate", "");

					engineMsgDao.insertEngineMsg(engineMsgMap); // 保存

					orderMap.put("EngineMsgId", engineMsgMap.get("id"));
					orderMap.put("OEMName", orderMap.get("OEMName"));
				}

			}
		}
		//String OrderNo = workOrderRepairService.getOrderNo(orderMap);// 后台自动生成工单编号
		/**
		 * <p>
		 *     自动生成工单编号，由 redis 更改为 sqlServer
		 * </p>
		 */
		String OrderNo = OrderGenerateUtil.getWorkOrderNo();
		orderMap.put("OrderNo", OrderNo);
		if (!orderMap.containsKey("CreateTime")) {
			orderMap.put("CreateTime", LocalTimeUtil.getRealCurrentTime());
		}
		orderMap.put("OrderId", "");// 用户保存插入工单成功返回的工单ID

		if (MapUtils.getIntValue(orderMap, "IsHaveDBEngineer", 0) == 1) {//指派了区域工程师
			orderMap.put("OrderStatus", "18"); // 18 待区域工程师处理

			// 设置推荐服务站的默认值
			orderMap.put("FirstStationId", -1);
			orderMap.put("SecondStationId", -2);
			orderMap.put("ThirdStationId", -3);
			List<Map<String, Object>> serviceStationList = (List<Map<String, Object>>) orderMap
					.get("ServiceStationList");
			if (serviceStationList != null && serviceStationList.size() > 0) {
				for (int i = 0; i < serviceStationList.size(); i++) {
					Map<String, Object> threeSSMap = new HashMap<>();
					Map<String, Object> serviceStationMap = serviceStationList.get(i);
					threeSSMap.put("BusinessNo", serviceStationMap.get("stationNo"));
					threeSSMap.put("CompanyNo", orderMap.get("CompanyNo"));
					ServiceStationT serviceStation = crmServiceDao
							.getServiceStationByBusinessNoAndCompanyNo(threeSSMap);
					if (serviceStation != null) {
						if (i == 0) {
							orderMap.put("FirstStationId", serviceStation.getId());
						} else if (i == 1) {
							orderMap.put("SecondStationId", serviceStation.getId());
						} else {
							orderMap.put("ThirdStationId", serviceStation.getId());
						}
					}
				}
			}

		} else {
			orderMap.put("OrderStatus", "4"); // 4 待服务商接单
			orderMap.put("AssignStationTime", LocalTimeUtil.getRealCurrentTime());
			List<Map<String, Object>> serviceStationList = (List<Map<String, Object>>) orderMap
					.get("ServiceStationList");
			if (serviceStationList != null && serviceStationList.size() > 0) {
				Map<String, Object> serviceStationMap = serviceStationList.get(0);

				orderMap.put("BusinessNo", serviceStationMap.get("stationNo"));
				ServiceStationT serviceStation = crmServiceDao.getServiceStationByBusinessNoAndCompanyNo(orderMap);
				if (serviceStation == null || serviceStation.getId() < 0) {
					LOG.info("服务站信息没有查询到");
					obj.put("status", 1);
					obj.put("msg", "服务站基础信息未查询到");
					obj.put("data", new JSONObject());
					return obj;
				}

				/**
				 * TODO MT2.0需求
				 * 如果400同步的服务站为虚拟服务站(用于创建MT单子的服务站)则给当前服务工单设置MT标签
				 */
				String businessNo = MapUtils.getString(serviceStationMap, "stationNo", "");
				String stationName = MapUtils.getString(serviceStationMap, "stationName", "");
				// 如果指派的服务站匹配2个条件之一，则当前服务站就为虚拟服务站(MT服务站)
				if(Objects.equals(this.stationNo, businessNo) || Objects.equals(this.stationName, stationName)) {
					// MtTag默认为0，1：表示当前服务工单为移动
					orderMap.put("MtTag", 1);
				}


				orderMap.put("ServiceStationId", serviceStation.getId().toString());

				/**
				 * 8、CRM同步功能单，一定会指派服务站（故障点到服务站的距离要计算一下）
				 */
				Map<String, Object> StationLatLon = workOrderRePairDao.getDistance(orderMap);
				// 获取距离和服务站经纬度
				String stationlonlat = StationLatLon.get("PositionLon") + "," + StationLatLon.get("PositionLat");
				String Faultlonlat = orderMap.get("LocLon") + "," + orderMap.get("LocLat");
				Double distance = 0.0;
				try {
					distance = GetDistance.getDistance(stationlonlat, Faultlonlat);
					orderMap.put("GuessDistance", distance);
				} catch (Exception e) {
					LOG.error("GuessDistance", e);
					// 获取故障点与服务站距离有误
					obj.put("status", 1);
					obj.put("msg", SMSEnum.type29.getName());
					obj.put("data", new JSONObject());
					return obj;
				}
			} else {
				LOG.info("指派服务站为空");
				obj.put("status", 1);
				obj.put("msg", "指派服务站为空");
				obj.put("data", new JSONObject());
				return obj;
			}

		}
		return null;
	}

	/**
	 * DCEC/XCEC 创建工单 @Title: crmCreatWorkOrder @Description:
	 * TODO(这里用一句话描述这个方法的作用) @param @param orderMap @param @return @return
	 * JSONObject @throws
	 */
	public JSONObject crmCreatWorkOrder(Map<String, Object> orderMap) {

		/**
		 * 1、定义返回结果
		 */
		JSONObject obj = new JSONObject();
		CompanyT company = companyTDao.getCompanyInfoByCompanyNo(orderMap.get("CompanyNo").toString());
		/**
		 * 2、根据电话号码获取APP系统的userid
		 */
		//xcec的售前工单  不验证手机号
		String salesServiceType = MapUtils.getString(orderMap, "salesServiceType", "");
		boolean xcecSalesServiceTypeFlag = company.getCompanyNo().equals("XCEC") && SALESSERVICE_TYPE.equals(salesServiceType);
		if (!xcecSalesServiceTypeFlag) {
            String customerPhone = orderMap.get("CustomerPhone").toString();
            List<UserT> users = loginDao.getUserByPhone(customerPhone);
            if (CollectionUtils.isNotEmpty(users)) {
                long lCustomerId = users.get(0).getId();
                orderMap.put("CustomerId", lCustomerId);
            }
		}
		/**
		 * 3、根据CompanyNo获取对应的Company信息
		 */

		if (company == null) {
			LOG.info("服务渠道没有查询到");
			// 返回给CRM系统错误信息（服务站信息没有查询到）
			obj.put("status", 1);
			obj.put("msg", "服务渠道未查询到");
			obj.put("data", new JSONObject());
			return obj;
		}
		orderMap.put("OrderChannel", company.getId());
		orderMap.put("OrderChannelName", company.getCompanyNo());

		/**
		 * 4、根据ESN获取对应的EngineMsgId、OEMName 4.1先根据发动机号ESN从发动机信息表EngineMsg中查询是否有数据
		 */
		EngineMsg engineMsg = engineMsgDao.getEngineMsgByESN(orderMap);
		EngineMsg engineMsgByAmt = engineMsgDao.getEngineMsgByAmtNo(orderMap);
		if (company.getCompanyNo().equals(CRMServiceConst.CCEC)) {
			// CCEC逻辑与其他渠道不同
			if (null == engineMsg) {
				obj.put("status", 1);
				obj.put("msg", "发动机信息未查询到");
				obj.put("data", new JSONObject());
				return obj;
			} else {
				orderMap.put("EngineMsgId", engineMsg.getId());
				orderMap.put("OEMName",
						StringUtils.isEmpty(engineMsg.getVehicleCompany()) ? "" : engineMsg.getVehicleCompany());
			}
		} else {
			// DCEC,DBU,XCEC报单发动机信息处理
			if (engineMsg != null) { // 如果发动机信息表EngineMsg中查询到数据
				orderMap.put("EngineMsgId", engineMsg.getId());
				orderMap.put("OEMName", (engineMsg.getVehicleCompany() == null) ? "" : engineMsg.getVehicleCompany());

			} else {
				// 发动机信息表EngineMsg中没有查询到数据，就根据发动机号(ESN)和服务渠道serviceChannel调用CRM接口查询发动机数据
				CRMResponeEntity cRMResponeEntity = CRMApiUtils.getCRMServiceApi()
						.verifyEngineInfo(company.getCompanyNo(), orderMap.get("ESN").toString());
				if (cRMResponeEntity.getStatus() == 0) {
					// 保存发动机信息表
					Map<String, Object> engineMsgMap = new HashedMap<String, Object>();
					engineMsgMap.put("ESN", orderMap.get("ESN"));
					engineMsgMap.put("SMN", cRMResponeEntity.getData().get("SMN"));
					engineMsgMap.put("equipmentNo", cRMResponeEntity.getData().get("equipmentNo"));
					engineMsgMap.put("vehicleCompany", cRMResponeEntity.getData().get("vehicleCompany"));
					engineMsgMap.put("engineType", cRMResponeEntity.getData().get("engineType"));
					engineMsgMap.put("manufactor", cRMResponeEntity.getData().get("manufactor"));
					engineMsgMap.put("serviceChannel", cRMResponeEntity.getData().get("serviceChannel"));
					engineMsgMap.put("saleDate", cRMResponeEntity.getData().get("saleDate"));

					engineMsgDao.insertEngineMsg(engineMsgMap); // 保存

					orderMap.put("EngineMsgId", engineMsgMap.get("id"));
					orderMap.put("OEMName", cRMResponeEntity.getData().get("vehicleCompany"));

				}
				/**
				 * DCEC amt 新增需求
				 * 增加判断，如果是DCEC需要判断amt
				 *
				 */
				if( CRMServiceConst.DCEC.equals(company.getCompanyNo()) ){
					if(engineMsg == null && engineMsgByAmt != null ){
					// 发动机信息表EngineMsg中没有查询到数据，就根据发动机号(ESN)和服务渠道serviceChannel调用CRM接口查询发动机数据
						CRMResponeEntity cRMResponeEntityByAmt = CRMApiUtils.getCRMServiceApi()
								.verifyEngineInfo(company.getCompanyNo(), orderMap.get("amtNo").toString());
						if (cRMResponeEntity.getStatus() == 0) {
							// 保存发动机信息表
							Map<String, Object> engineMsgMap = new HashedMap<String, Object>();

							engineMsgMap.put("SMN", cRMResponeEntity.getData().get("SMN"));
							engineMsgMap.put("equipmentNo", cRMResponeEntity.getData().get("equipmentNo"));
							engineMsgMap.put("vehicleCompany", cRMResponeEntity.getData().get("vehicleCompany"));
							engineMsgMap.put("engineType", cRMResponeEntity.getData().get("engineType"));
							engineMsgMap.put("manufactor", cRMResponeEntity.getData().get("manufactor"));
							engineMsgMap.put("serviceChannel", cRMResponeEntity.getData().get("serviceChannel"));
							engineMsgMap.put("saleDate", cRMResponeEntity.getData().get("saleDate"));
							/**
							 * 添加amtNo
							 * esn为空
							 */
							engineMsgMap.put("ESN", orderMap.get("ESN") == null ? "" : orderMap.get("ESN"));
							engineMsgMap.put("amtNo", cRMResponeEntity.getData().get("amtNo"));

							engineMsgDao.insertEngineMsg(engineMsgMap); // 保存

							orderMap.put("EngineMsgId", engineMsgMap.get("id"));
							orderMap.put("OEMName", cRMResponeEntity.getData().get("vehicleCompany"));

						}
					}
				}
			}
		}

		/**
		 * 5、获取工单编号
		 */
		//String OrderNo = workOrderRepairService.getOrderNo(orderMap);// 后台自动生成工单编号
		/**
		 * <p>
		 *     自动生成工单编号，由 redis 更改为 sqlServer
		 * </p>
		 */
		String OrderNo = OrderGenerateUtil.getWorkOrderNo();
		orderMap.put("OrderNo", OrderNo);
		orderMap.put("CreateTime", LocalTimeUtil.getRealCurrentTime());
		orderMap.put("OrderId", "");// 用户保存插入工单成功返回的工单ID

		/**
		 * 6、根据stationNo、serviceChannel获取服务站信息
		 */
		ServiceStationT serviceStation = crmServiceDao.getServiceStationByBusinessNoAndCompanyNo(orderMap);
		if (serviceStation == null || serviceStation.getId() < 0) {
			LOG.info("服务站信息没有查询到");
			// 返回给CRM系统错误信息（服务站信息没有查询到）
			obj.put("status", 1);
			obj.put("msg", "服务站未查询到");
			obj.put("data", new JSONObject());
			return obj;
		}
		orderMap.put("ServiceStationId", serviceStation.getId().toString());

		/**
		 * 7、CRM同步功能单，一定会指派服务站（故障点到服务站的距离要计算一下）
		 */
		Map<String, Object> StationLatLon = workOrderRePairDao.getDistance(orderMap);
		// 获取距离和服务站经纬度
		String stationlonlat = StationLatLon.get("PositionLon") + "," + StationLatLon.get("PositionLat");
		String Faultlonlat = orderMap.get("LocLon") + "," + orderMap.get("LocLat");
		Double distance = 0.0;
		try {
			distance = GetDistance.getDistance(stationlonlat, Faultlonlat);
			orderMap.put("GuessDistance", distance);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			// 获取故障点与服务站距离有误
			obj.put("status", 1);
			obj.put("msg", SMSEnum.type29.getName());
			obj.put("data", new JSONObject());
			return obj;
		}

		/**
		 * 8、根据服务站Id获取服务站的区域服务经理（服务站在线保修，工单创建完成后，工单负责人是区域服务经理）
		 */
		if (company.getCompanyNo().equals("XCEC")) {
			if (orderMap.get("OrderType").toString().equals("0")) { // 发动机维修
					//149  ------  400报单，  400改派时  考虑为  大工匠工单
				if (orderMap.get("OrderSource").toString().equals("2")) { // 400 报修
					//大工匠工单 直接为待服务经理确认
					if (MapUtils.getInteger(orderMap,"IsTechSupport",0)==1) {
						orderMap.put("OrderStatus", "2"); // 2 待服务经理通过
						orderMap.put("roleNo", "'R0070'");
					}else if (orderMap.get("IsOutside").toString().equals("1") && distance >= 300) { // 外出里程>=300公里,需要审批
						orderMap.put("OrderStatus", "2"); // 2 待服务经理通过
						orderMap.put("roleNo", "'R0070'");
						List<Map<String, Object>> AreaManagerMap = workOrderRePairDao.getAreaManager(orderMap);
						if (AreaManagerMap == null || AreaManagerMap.size() == 0) {
							// 未查询到审核人，不能创建工单
							obj.put("status", 1);
							obj.put("msg", SMSEnum.type23.getName());
							obj.put("data", new JSONObject());
							return obj;
						}
						//是否需要同步工单状态
//						orderMap.put("SynStatusFlag", true);
					} else {
						orderMap.put("OrderStatus", "4"); // 4 待服务商接单
						orderMap.put("AssignStationTime", LocalTimeUtil.getRealCurrentTime());
					}
				} else if (orderMap.get("OrderSource").toString().equals("3")) { // 服务站 CRM报修
					if (orderMap.get("IsOutside").toString().equals("1") && distance >= 300) { // 外出里程>=300公里,需要审批
						orderMap.put("OrderStatus", "2"); // 2 待服务经理通过
						orderMap.put("roleNo", "'R0070'");
						List<Map<String, Object>> AreaManagerMap = workOrderRePairDao.getAreaManager(orderMap);
						if (AreaManagerMap == null || AreaManagerMap.size() == 0) {
							// 未查询到审核人，不能创建工单
							obj.put("status", 1);
							obj.put("msg", SMSEnum.type23.getName());
							obj.put("data", new JSONObject());
							return obj;
						}
					} else {
						orderMap.put("OrderStatus", "6"); // 6 待派服务技师
					}
				} else if (orderMap.get("OrderSource").equals("4")) { // 400改派
					//大工匠工单 直接为待服务经理确认
					if (MapUtils.getInteger(orderMap,"IsTechSupport",0)==1) {
						orderMap.put("OrderStatus", "2"); // 2 待服务经理通过
						orderMap.put("roleNo", "'R0070'");
					}else {
						orderMap.put("OrderStatus", "4"); // 4 待服务商接单
						orderMap.put("AssignStationTime", LocalTimeUtil.getRealCurrentTime());
					}
				}
			} else // 售时维修
			{
				//是否是大工匠工单 去除
				orderMap.remove("IsTechSupport");
				//技术支持内容  去除
				orderMap.remove("TechSupportContent");
				if (orderMap.get("IsOutside").toString().equals("0")) { // 售时工单，非外出
					orderMap.put("OrderStatus", "6"); // 6 待派服务技师
				} else {
					orderMap.put("OrderStatus", "2"); // 2 待服务经理通过
					orderMap.put("roleNo", "'R0070'");
					List<Map<String, Object>> AreaManagerMap = workOrderRePairDao.getAreaManager(orderMap);
					if (AreaManagerMap == null || AreaManagerMap.size() == 0) {
						// 未查询到审核人，不能创建工单
						obj.put("status", 1);
						obj.put("msg", SMSEnum.type23.getName());
						obj.put("data", new JSONObject());
						return obj;
					}
				}
			}
		} else if(CRMServiceConst.DCEC.equals(company.getCompanyNo())) {
			/*
				新增DCEC分支，处理DCEC的特殊业务逻辑
				1、服务商SF报修，工单状态为【待派技师】，其他为待经理确认【待经理确认】
			 */
			if(orderMap.get("OrderSource").equals("3")){//服务站CRM工单报修
				orderMap.put("OrderStatus", "6"); // 6 待派服务技师
			} else {
				orderMap.put("OrderStatus", "2"); // 2 待服务经理通过
			}
			orderMap.put("roleNo", "'R0070'");
			List<Map<String, Object>> AreaManagerMap = workOrderRePairDao.getAreaManager(orderMap);
			if (AreaManagerMap == null || AreaManagerMap.size() == 0) {
				// 未查询到审核人，不能创建工单
				obj.put("status", 1);
				obj.put("msg", SMSEnum.type23.getName());
				obj.put("data", new JSONObject());
				return obj;
			}
		} else {
			orderMap.put("OrderStatus", "2"); // 2 待服务经理通过
			// CRM创建工单（是否外出为必填项）工单状态为 待服务经理确认
			orderMap.put("roleNo", "'R0070'");
			List<Map<String, Object>> AreaManagerMap = workOrderRePairDao.getAreaManager(orderMap);
			if (AreaManagerMap == null || AreaManagerMap.size() == 0) {
				// 未查询到审核人，不能创建工单
				obj.put("status", 1);
				obj.put("msg", SMSEnum.type23.getName());
				obj.put("data", new JSONObject());
				return obj;
			}
		}
		return null;
	}

	/**
	 * App 用户在线报修未指定服务站 @Title: updateWorkOrder @Description:
	 * TODO(这里用一句话描述这个方法的作用) @param @param orderMap @param @return @return
	 * JSONObject @throws
	 */
	public JSONObject updateWorkOrder(Map<String, Object> orderMap, Map<String, Object> oldWorkOrderMap) {
		/**
		 * 1、定义返回结果
		 */
		JSONObject jsonObject = new JSONObject();
		/**
		 * 2、查询工单服务站信息
		 */
		ServiceStationT serviceStation = crmServiceDao.getServiceStationByBusinessNoAndCompanyNo(orderMap);
		if (serviceStation == null || serviceStation.getId() < 0) {
			LOG.info("服务站信息没有查询到");
			// 返回给CRM系统错误信息（服务站信息没有查询到）
			jsonObject.put("status", 1);
			jsonObject.put("msg", "服务站未查询到");
			jsonObject.put("data", new JSONObject());
			return jsonObject;
		}
		oldWorkOrderMap.put("ServiceStationId", serviceStation.getId().toString());

		if (MapUtils.getString(orderMap, "CompanyNo", "").equals("XCEC")) {
			orderMap.put("ServiceStationId", serviceStation.getId().toString());
			orderMap.put("OrderChannel", oldWorkOrderMap.get("OrderChannel"));
			orderMap.put("OrderChannelName", oldWorkOrderMap.get("OrderChannelName"));
			oldWorkOrderMap.put("OrderStatus", "4");
			oldWorkOrderMap.put("AssignStationTime", LocalTimeUtil.getRealCurrentTime());
			oldWorkOrderMap.put("IsOutside", orderMap.get("IsOutside"));
		} else {
			if(CRMServiceConst.DCEC.equals(MapUtils.getString(orderMap, "CompanyNo", ""))){
				oldWorkOrderMap.put("IsOutside", orderMap.get("IsOutside"));
			}
			/**
			 * 3、根据服务站Id获取服务站的区域服务经理（服务站在线保修，工单创建完成后，工单负责人是区域服务经理）
			 */
			oldWorkOrderMap.put("roleNo", "'R0070'");
			/**
			 * 3.1 根据ServiceStationId和OrderChannel查询到对应的区域服务经理
			 */
			orderMap.put("ServiceStationId", serviceStation.getId().toString());
			orderMap.put("OrderChannel", oldWorkOrderMap.get("OrderChannel"));
			orderMap.put("OrderChannelName", oldWorkOrderMap.get("OrderChannelName"));
			List<Map<String, Object>> AreaManagerMap = workOrderRePairDao.getAreaManager(orderMap);

			oldWorkOrderMap.put("OrderStatus", "2");
			if (null == AreaManagerMap || AreaManagerMap.size() == 0) {

				// 未查询到审核人，不能创建工单
				jsonObject.put("status", 1);
				jsonObject.put("msg", SMSEnum.type23.getName());
				jsonObject.put("data", new JSONObject());
				return jsonObject;
			}
		}

		/**
		 * 4、判断是否需要外出（如果需要外出则故障点到服务站的距离要计算一下）
		 */
		Map<String, Object> StationLatLon = workOrderRePairDao.getDistance(orderMap);
		// 获取服务站经纬度、距离
		String stationlonlat = StationLatLon.get("PositionLon") + "," + StationLatLon.get("PositionLat");
		String Faultlonlat = orderMap.get("LocLon") + "," + orderMap.get("LocLat");
		Double distance = 0.0;
		try {
			distance = GetDistance.getDistance(stationlonlat, Faultlonlat);
			oldWorkOrderMap.put("GuessDistance", distance);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			// 获取故障点与服务站距离有误
			jsonObject.put("status", 1);
			jsonObject.put("msg", SMSEnum.type29.getName());
			jsonObject.put("data", new JSONObject());
			return jsonObject;
		}

		return null;
	}

	public void saveSSRepair(Map<String, Object> serviceStationInfoMap, SSRepairOperation operation) {
		int saveSSRepairResult = 0;
		serviceStationInfoMap.put("authorizationLevel", MapUtils.getString(serviceStationInfoMap, "authorizationLevel", ""));
		if (operation.equals(SSRepairOperation.SAVE)) {
			/* 授权编号删除，注释不用
			Long serviceStationId = MapUtils.getLong(serviceStationInfoMap,"ServiceStationID");
			Long companyId =  MapUtils.getLong(serviceStationInfoMap,"CompanyID");
			ssRepairTDao.deleteSSRepairTByID(serviceStationId,companyId);*/
			saveSSRepairResult = crmServiceDao.insertSSRepairInfo(serviceStationInfoMap);
		} else {
			saveSSRepairResult = crmServiceDao.updateSSRepairInfoByServiceStationID(serviceStationInfoMap);
		}
		if (saveSSRepairResult < 1) {
			LOG.error("SSRepair保存失败" + JsonUtils.toJsonString(serviceStationInfoMap));
		}
	}

	private void saveSSHasCompany(String vehicleCompanies, Long companyId, Long serviceStationId) {
		if ("All".equals(vehicleCompanies)) {
			// 1.删除原有授权信息(当前仅有DBU含有此逻辑，故可以通过serviceStationId直接删除所有信息)
			ssHasCompanyDao.deleteSSHasCompanyByServiceStationId(serviceStationId);
			ssHasCompanyDao.createAllRelation(serviceStationId);
		}

		//1.删除原有授权信息(当前仅有DBU含有此逻辑，故可以通过serviceStationId直接删除所有信息)
		//ssHasCompanyDao.deleteSSHasCompanyByServiceStationId(serviceStationId);
		// 2.处理前端传输的主机厂参数
		/*if (StringUtils.isNotEmpty(vehicleCompanies)) {
			List<String> list = Arrays.asList(vehicleCompanies.split(","));
			if (CollectionUtils.isNotEmpty(list)) {
				// 遍历前端传输的主机厂参数
				for (String companyName : list) {
					// 通过主机厂名称查询企业表数据
					CompanyT vehicleCompany = companyTDao.getCompanyInfoByCompanyName(companyName);
					if (null == vehicleCompany) {
						// TODO: 2019/7/29 不存在主机厂信息
					} else {
						ssHasCompanyDao.saveSSHasCompany(serviceStationId, vehicleCompany.getId());
					}
				}
			}
		} else {

		}*/
	}

	private void saveSSHasServiceType(String serviceTypes, Long companyId, Long serviceStationId) {
		ssHasServiceTypeDao.deleteSSHasServiceTypeByServiceStationId(serviceStationId);
		if (StringUtils.isNotEmpty(serviceTypes)) {
			List<String> list = Arrays.asList(serviceTypes.split(","));
			crmServiceDao.SSHasServiceType(serviceStationId, list);
		}
	}

	private void saveSSHasVehicleType(String vehicleTypes, Long companyId, Long serviceStationId) {
		ssHasVehicleTypeDao.deleteSSHasVehicleTypeByServiceStationId(serviceStationId);
		if (StringUtils.isNotEmpty(vehicleTypes)) {
			List<String> list = Arrays.asList(vehicleTypes.split(","));
			crmServiceDao.SSHasVehicleType(serviceStationId, list);
		}
	}

//	private void saveSSHasEngineType(String engineTypes, Long companyId, Long serviceStationId) {
//		//删除原有授权信息
//		ssHasEngineTypeDao.deleteSSHasEngineTypeByServiceStationId(serviceStationId, companyId);
//		if (StringUtils.isNotEmpty(engineTypes)) {
//			List<String> list = Arrays.asList(engineTypes.split(","));
//			if (CollectionUtils.isNotEmpty(list)) {
//                String typeNames = "'" + StringUtils.join(list, "','") + "'";
//                List<String> stringList = StringToool.getStringList(typeNames, ",");
//                List<Long> engineIDs = crmServiceDao.getEngineTypeByTypename(stringList);
//                if (engineIDs.size() > 0) {
//                    crmServiceDao.SSHasEngineType(serviceStationId, companyId, engineIDs);
//                }
//            }
//		}
//	}

	private void saveSSHasSMN(String authorizedMode, Long companyId, Long serviceStationId) {
		ssHasSMNDao.deleteSSHasSMNByServiceStationId(serviceStationId);
		if (StringUtils.isEmpty(authorizedMode)) {
			return;
		}
		List<String> serviceModelNameList = Arrays.asList(authorizedMode.split(";"));
		if (CollectionUtils.isNotEmpty(serviceModelNameList)) {
			serviceModelNameList.forEach(serviceModelName -> {
				serviceModelName = serviceModelName.trim();
				Map<String, Object> smnMap = serviceModelNameDao.getServiceModelName(serviceModelName);
				if (MapUtils.isNotEmpty(smnMap)) {
					Long serviceModelNameId = MapUtils.getLong(smnMap, "ID");
					SSHasSMN hasSMN = new SSHasSMN();
					hasSMN.setCompanyId(companyId);
					hasSMN.setServiceStationId(serviceStationId);
					hasSMN.setServiceModelNameId(serviceModelNameId);
					hasSMN.setServiceModelName(serviceModelName);
					hasSMN.setFlag(0);
					hasSMN.setCreator(companyId);
					hasSMN.setCreateTime(LocalTimeUtil.getRealCurrentTime());
					ssHasSMNDao.insertSelective(hasSMN);
				} else {
					// TODO: 2019/7/26 增加未查询到SMN日志
				}
			});
		} else {
			// TODO: 2019/7/26 未查询到SMN
		}
	}

	/**
	 * DBU更新工单负责人和DBU消息提醒消息发送记录信息 @Title: saveWorkOrderPrincipalAndMessageInfo @Description:
	 * TODO(这里用一句话描述这个方法的作用) @param @param orderMap @param @return @return
	 * JSONObject @throws
	 */
	public JSONObject saveWorkOrderPrincipalAndMessageInfoFromDBU(Map<String, Object> orderMap) {

		String currentTime = LocalTimeUtil.getRealCurrentTime();
		List<Map<String, Object>> sendList = new ArrayList<Map<String, Object>>();
		// 记录用户行为日志（需要把上面保存成功的工单Id放进map中）
		if (MapUtils.getIntValue(orderMap, "IsHaveDBEngineer", 0) == 1) {
			String engineerPhone = orderMap.get("DBEngineerPhone").toString();
			List<UserT> userList = loginDao.getUserByPhone(engineerPhone);
			if (userList != null && userList.size() > 0) {
				orderMap.put("ProcessorId", 0);
				orderMap.put("PrincipalId", userList.get(0).getId());
				orderMap.put("IsPrincipal", 1);

				// 1、记录用户行为日志（需要把上面保存成功的工单Id放进map中）
				workOrderTServiceImpl.saveOperation(MapUtils.getLongValue(orderMap, "OrderId", 0), -1,
						MapUtils.getIntValue(orderMap, "OrderStatus", 0), "CAC派单区域", "0.00", "0.00", "", "", 0, -1,
						currentTime);
				// 2、记录工单负责人表
				String smstext = "您有新工单信息，工单号" + orderMap.get("OrderNo") + "，请尽快处理。";
				workOrderTServiceImpl.savePrincipal(MapUtils.getLongValue(orderMap, "OrderId", 0),
						MapUtils.getIntValue(orderMap, "OrderStatus", 0), 1, userList.get(0).getId(), -1, currentTime);
				// 3、发送短信消息提醒
				//SmsTool.sendSms(userList.get(0).getPhone(), smstext);
				smstext = dbuMessageService.sendAssignMessage(userList.get(0), MapUtils.getLongValue(orderMap, "OrderId", 0));
				// APP推送
				noticeService.push(2, 1, MapUtils.getLong(orderMap, "OrderId", 0L), userList.get(0).getId(),
						userList.get(0).getUserName(), "新工单提醒", smstext, smstext, 0L);
				// 5、保存通知消息记录
				List<Map<String, Object>> notifyRecordTMapList = new ArrayList<>();
				notifyRecordTMapList
						.add(workOrderTServiceImpl.saveMsgOperation(MapUtils.getLongValue(orderMap, "OrderId", 0), 2, 1,
								userList.get(0).getId(), smstext, 1, currentTime, "", -1));
				if (CollectionUtils.isNotEmpty(notifyRecordTMapList)) {
					workOrderRePairDao.saveMsgOperation(notifyRecordTMapList);
				}
				// 6、返回保存状态
				JSONObject obj = new JSONObject();
				obj.put("APPOrderNo", orderMap.get("OrderNo"));

				JSONObject jsonObject = new JSONObject();
				jsonObject.put("data", obj);
				jsonObject.put("status", SMSEnum.type0.getIndex());
				jsonObject.put("msg", SMSEnum.type0.getName());
				return jsonObject;
			} else {
				// 6、返回保存状态
				JSONObject obj = new JSONObject();
				obj.put("APPOrderNo", orderMap.get("OrderNo"));

				JSONObject jsonObject = new JSONObject();
				jsonObject.put("data", obj);
				jsonObject.put("status", 0);
				jsonObject.put("msg", "工单创建成功，区域工程师在APP系统未注册");
				return jsonObject;
			}

		} else {
			String objMsg = "";
			String smsTipText = "";
			orderMap.put("ServiceStationID", orderMap.get("ServiceStationId"));
			if (orderMap.containsKey("scenarioStatus") && orderMap.get("scenarioStatus").toString().equals("10")) {// APP服务商报修-CAC确认服务商通过
				// 1、保存工单操作记录表

				workOrderTServiceImpl.saveOperation(MapUtils.getLongValue(orderMap, "OrderId", 0), -1,
						MapUtils.getIntValue(orderMap, "OrderStatus", 0), "服务站挂号CAC审核通过",
						MapUtils.getString(orderMap, "LocLon", ""), MapUtils.getString(orderMap, "LocLat", ""),
						MapUtils.getString(orderMap, "Location", ""), "", 0, -1, currentTime);
				smsTipText = "待派技师工单提醒";
			} else {
				// 1、保存工单操作记录表
				workOrderTServiceImpl.saveOperation(MapUtils.getLongValue(orderMap, "OrderId", 0), -1,
						MapUtils.getIntValue(orderMap, "OrderStatus", 0), "CAC指派服务站", "0.00", "0.00", "", "", 0, -1,
						currentTime);
				smsTipText = "新工单提醒";
			}
			List<UserT> userTS = userTDao.getUserTByServiceStationId(orderMap);

			if (CollectionUtils.isNotEmpty(userTS)) {
				for (UserT userZZ : userTS) {
					if (userZZ != null) {
						// 2、记录工单负责人表

						workOrderTServiceImpl.savePrincipal(MapUtils.getLongValue(orderMap, "OrderId", 0),
								MapUtils.getIntValue(orderMap, "OrderStatus", 0), 1, userZZ.getId(), -1, currentTime);
						// 3、发送短信消息提醒
						//SmsTool.sendSms(userZZ.getPhone(), smstext);
						String newSmstext = dbuMessageService.sendAssignMessage(userZZ, MapUtils.getLongValue(orderMap, "OrderId", 0));
						// 通过UserName拿到ClientId
						noticeService.push(2, 1, MapUtils.getLong(orderMap, "OrderId", 0L), userZZ.getId(),
								userZZ.getUserName(), smsTipText, newSmstext, newSmstext, 0L);
						// 5、保存通知消息记录
						List<Map<String, Object>> notifyRecordTMapList = new ArrayList<>();
						notifyRecordTMapList.add(workOrderTServiceImpl.saveMsgOperation(
								Long.parseLong(orderMap.get("OrderId").toString()), 2, 1, userZZ.getId(), newSmstext, 1,
								currentTime, "", -1));
						if (CollectionUtils.isNotEmpty(notifyRecordTMapList)) {
							workOrderRePairDao.saveMsgOperation(notifyRecordTMapList);
						}
					}
				}
			} else {
				objMsg = "服务站站长在APP系统未注册";
			}
			List<UserT> xXYUserTS = userTDao.getMsgUserTByServiceStationId(orderMap);
			if (CollectionUtils.isNotEmpty(xXYUserTS)) {
				for (UserT userXXY : xXYUserTS) {
					if (userXXY != null) {
						// 2、记录工单负责人表

						workOrderTServiceImpl.savePrincipal(Long.parseLong(orderMap.get("OrderId").toString()),
								Integer.parseInt(orderMap.get("OrderStatus").toString()), 1, userXXY.getId(), -1,
								currentTime);
						// 3、发送短信消息提醒
						//SmsTool.sendSms(userXXY.getPhone(), smstext);
						String newSmstext = dbuMessageService.sendAssignMessage(userXXY, MapUtils.getLongValue(orderMap, "OrderId", 0));
						// 发送推送
						noticeService.push(2, 1, MapUtils.getLong(orderMap, "OrderId", 0L), userXXY.getId(),
								userXXY.getUserName(), smsTipText, newSmstext, newSmstext, 0L);
						// 5、保存通知消息记录
						List<Map<String, Object>> notifyRecordTMapList = new ArrayList<>();
						notifyRecordTMapList.add(workOrderTServiceImpl.saveMsgOperation(
								Long.parseLong(orderMap.get("OrderId").toString()), 2, 1, userXXY.getId(), newSmstext, 1,
								currentTime, "", -1));
						if (CollectionUtils.isNotEmpty(notifyRecordTMapList)) {
							workOrderRePairDao.saveMsgOperation(notifyRecordTMapList);
						}
					}
				}
			} else {
				objMsg = (objMsg + "服务站信息员在APP系统未注册");
			}
			// 6、返回保存状态
			JSONObject obj = new JSONObject();
			obj.put("APPOrderNo", orderMap.get("OrderNo"));

			JSONObject jsonObject = new JSONObject();
			jsonObject.put("data", obj);
			jsonObject.put("status", 0);
			jsonObject.put("msg", objMsg);
			return jsonObject;
		}
	}

	/**
	 * @return net.sf.json.JSONObject
	 * @Author Joe
	 * @Description 更新工单负责人和消息发送记录信息 @Title: saveWorkorderPrincipalAndMessageInfoFromXCEC
	 * @Date 9:47 AM 2019/9/4
	 * @Param [orderMap]
	 **/
	private JSONObject saveWorkorderPrincipalAndMessageInfoFromXCEC(Map<String, Object> orderMap) {
		String currentTime = LocalTimeUtil.getRealCurrentTime();
		List<Map<String, Object>> sendList = new ArrayList<Map<String, Object>>();
		String objMsg = "";
		String smstext = "您有新工单信息，工单号" + orderMap.get("OrderNo") + "，请尽快处理。";
		String smsTipText = "新工单提醒";
		orderMap.put("ServiceStationID", orderMap.get("ServiceStationId"));
		List<UserT> userTS = userTDao.getUserTByServiceStationId(orderMap);

		if (orderMap.get("OrderStatus").toString().equals("2")) { // 带区域经理确认
			return this.saveWorkOrderPrincipalAndMessageInfo(orderMap);
		} else // 待派服务技师 or 待服务商接单
		{
			// 记录工单操作状态记录表
			workOrderRePairDao.saveOperation(orderMap);
			// 记录用户行为日志（需要把上面保存成功的工单Id放进map中）
			if (CollectionUtils.isNotEmpty(userTS)) {
				for (UserT userZZ : userTS) {
					if (userZZ != null) {
						// 2、记录工单负责人表

						workOrderTServiceImpl.savePrincipal(Long.parseLong(orderMap.get("OrderId").toString()),
								Integer.parseInt(orderMap.get("OrderStatus").toString()), 1, userZZ.getId(), -1,
								currentTime);
						// 3、发送短信消息提醒
						SmsUtils.sendMessage(userZZ.getPhone(), smstext);
						List<Map<String, Object>> notifyRecordTMapList = new ArrayList<>();
						notifyRecordTMapList.add(workOrderTServiceImpl.saveMsgOperation(
								Long.parseLong(orderMap.get("OrderId").toString()), 2, 1, userZZ.getId(), smstext, 1,
								currentTime, "", -1));
						if (CollectionUtils.isNotEmpty(notifyRecordTMapList)) {
							workOrderRePairDao.saveMsgOperation(notifyRecordTMapList);
						}
						// APP推送
						noticeService.push(2, 1, MapUtils.getLong(orderMap, "OrderId", 0L), userZZ.getId(),
								userZZ.getUserName(), smsTipText, smstext, smstext, 0L);
					}
				}
			} else {
				objMsg = "服务站站长在APP系统未注册";
			}
			List<UserT> xXYUserTS = userTDao.getMsgUserTByServiceStationId(orderMap);
			if (CollectionUtils.isNotEmpty(xXYUserTS)) {
				for (UserT userXXY : xXYUserTS) {
					if (userXXY != null) {
						// 2、记录工单负责人表

						workOrderTServiceImpl.savePrincipal(Long.parseLong(orderMap.get("OrderId").toString()),
								Integer.parseInt(orderMap.get("OrderStatus").toString()), 1, userXXY.getId(), -1,
								currentTime);
						// 3、发送短信消息提醒
						SmsUtils.sendMessage(userXXY.getPhone(), smstext);
						List<Map<String, Object>> notifyRecordTMapList = new ArrayList<>();
						notifyRecordTMapList.add(workOrderTServiceImpl.saveMsgOperation(
								Long.parseLong(orderMap.get("OrderId").toString()), 2, 1, userXXY.getId(), smstext, 1,
								currentTime, "", -1));
						if (CollectionUtils.isNotEmpty(notifyRecordTMapList)) {
							workOrderRePairDao.saveMsgOperation(notifyRecordTMapList);
						}
						// APP推送
						noticeService.push(2, 1, MapUtils.getLong(orderMap, "OrderId", 0L), userXXY.getId(),
								userXXY.getUserName(), smsTipText, smstext, smstext, 0L);
					}
				}
			} else {
				objMsg = (objMsg + "服务站信息员在APP系统未注册");
			}
		}

		// 6、返回保存状态
		JSONObject obj = new JSONObject();
		if (orderMap.containsKey("OrderNoCrm")) {
			obj.put("CRMNo", orderMap.get("OrderNoCrm"));
		}
		obj.put("OrderNo", orderMap.get("OrderNo"));

		JSONObject jsonObject = new JSONObject();
		jsonObject.put("data", obj);
		jsonObject.put("status", 0);
		jsonObject.put("msg", objMsg);
		return jsonObject;
	}

	/**
	 * 更新工单负责人和消息发送记录信息 @Title: saveWorkOrderPrincipalAndMessageInfo @Description:
	 * TODO(这里用一句话描述这个方法的作用) @param @param orderMap @param @return @return
	 * JSONObject @throws
	 */
	public JSONObject saveWorkOrderPrincipalAndMessageInfo(Map<String, Object> orderMap) {
		/**
		 * 10、保存工单负责人信息
		 */
		JSONObject obj = new JSONObject();
		//大区经理审批，服务经理不可见
		WorkOrderT workOrderT = workOrderTDao.getWorkOrderTByOrderId(MapUtils.getLong(orderMap,"OrderId"));
		if(null != workOrderT && workOrderT.getIsTechSupport() == 1){
			orderMap.put("IsShowManager", 0);
		}
		// 记录用户行为日志（需要把上面保存成功的工单Id放进map中）
		int saveOperationResult = workOrderRePairDao.saveOperation(orderMap);

		if (saveOperationResult < 1) {
			LOG.info("工单记录保存失败 工单id:" + orderMap.get("OrderId").toString());
		}
		// 大工匠工单
		Integer integer = MapUtils.getInteger(orderMap, "IsTechSupport", 0);
		List<Map<String, Object>> AreaManagerMap = new ArrayList<>();
		if (1==integer) {
			AreaManagerMap = workOrderRePairDao.getManager(orderMap);
		}else {
			AreaManagerMap = workOrderRePairDao.getAreaManager(orderMap);
		}
		List<Map<String, Object>> sendList = new ArrayList<Map<String, Object>>();

		for (Map<String, Object> map : AreaManagerMap) {
			orderMap.put("PrincipalId", map.get("ID"));
			orderMap.put("IsPrincipal", 1);
			int savePrincipalResult = workOrderRePairDao.savePrincipal(orderMap);
			if (savePrincipalResult < 1) {
				LOG.info("工单负责人保存失败 工单id:" + orderMap.get("OrderId").toString());
			}
		}
		// 工单保存成功，此时状态为 待服务经理确认，需要给服务经理发送消息，区域服务经理信息已经在上面查出来，直接可以用
		sendList.addAll(AreaManagerMap);

		// 准备发送信息
		Map<String, Object> otherMap = new HashMap<String, Object>();
		String smsgbody = msgbody;
		smsgbody = smsgbody.replace("***", orderMap.get("OrderNo").toString());
		if(workOrderT.getOrderChannel() == 1){
			smsgbody = smsgbody + "属于\"" + workOrderT.getSellType() + "\"" + (StringUtils.isNotBlank(workOrderT.getServiceSubtype()) ? "-" + workOrderT.getServiceSubtype() : "") + "，";
		}
		smsgbody = smsgbody + "请尽快处理！";
		String stransmsg = transmsg;
		stransmsg = stransmsg.replace("***", orderMap.get("OrderNo").toString());
		if(workOrderT.getOrderChannel() == 1){
			stransmsg = stransmsg + "属于\"" + workOrderT.getSellType() + "\"" + (StringUtils.isNotBlank(workOrderT.getServiceSubtype()) ? "-" + workOrderT.getServiceSubtype() : "") + "，";
		}
		stransmsg = stransmsg + "请尽快处理！";
		otherMap.put("msgBody", smsgbody);// (,,,,)
		otherMap.put("msgTransMsg", stransmsg);
		otherMap.put("msgTitle", msgtitle);
		otherMap.put("function", msgFunctionNew);
		otherMap.put("category", msgCategoryNew);
		otherMap.put("ProcessorId", 0);
		// 开始发送消息(返回结果集为发送结果，要存入数据库，作为记录)
		List<Map<String, Object>> sendMsgResultList = asyncTask.sendMsg(orderMap, sendList, 1, 1,
				otherMap);
		// 将信息发送结果记录到数据库
		int saveMsgOperationResult = 0;
		if (CollectionUtils.isNotEmpty(sendMsgResultList)) {
			saveMsgOperationResult = workOrderRePairDao.saveMsgOperation(sendMsgResultList);
		}
		if (saveMsgOperationResult < 1) {
			LOG.info("信息发送记录保存失败 工单id:" + orderMap.get("OrderId").toString());
		}
		// 返回客户端通知工单保存成功
		JSONObject jsb = new JSONObject();
		try {
			if (orderMap.containsKey("OrderNoCrm")) {
				jsb.put("CRMNo", orderMap.get("OrderNoCrm"));
			}
			jsb.put("OrderNo", orderMap.get("OrderNo"));
			obj.put("data", jsb);
			obj.put("status", SMSEnum.type0.getIndex());
			obj.put("msg", SMSEnum.type0.getName());
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return obj;
	}

	/**
	 * @return java.util.Map<java.lang.String, java.lang.Object>
	 * @Author Joe
	 * @Description 将APP工单信息参数转化成CRM接口字段信息
	 * @Date 3:57 PM 2019/7/4
	 * @Param [map]
	 **/
	public Map<String, Object> appWorkOrderStatusToCrmWorkOrderData(Map<String, Object> orderMap,
																	Map<String, Object> statusMap, String crmStationNo) {

		Map<String, Object> crmOrderMap = new HashedMap<String, Object>();
		/**
		 * @Description orderMap配置字段orderNo、oldOrderNo、CRMNo、serviceCar、planMileage
		 * travelMileage、reviseMileage、remark
		 **/
		if (orderMap.containsKey("OrderNo")) {
			crmOrderMap.put("orderNo", orderMap.get("OrderNo"));
		}
		if (orderMap.containsKey("RelOrderIdOld")) {
			long relOrderIdOld = MapUtils.getLongValue(orderMap, "RelOrderIdOld", 0);
			Map<String, Object> oldOrderMap = crmServiceDao.getOrderNoByOrderId(relOrderIdOld);
			if (oldOrderMap != null && oldOrderMap.containsKey("OrderNo")) {
				crmOrderMap.put("oldOrderNo", MapUtils.getString(oldOrderMap, "OrderNo", ""));
			} else {
				crmOrderMap.put("oldOrderNo", "");
			}

		} else {
			crmOrderMap.put("oldOrderNo", "");
		}
		if (orderMap.containsKey("OrderNoCrm")) {
			crmOrderMap.put("CRMNo", orderMap.get("OrderNoCrm"));
		} else {
			crmOrderMap.put("CRMNo", "");
		}
		crmOrderMap.put("stationNo", crmStationNo);
		if (orderMap.containsKey("ServiceCarNo")) {
			crmOrderMap.put("serviceCar", orderMap.get("ServiceCarNo"));
		} else {
			crmOrderMap.put("serviceCar", "");
		}

		if (orderMap.containsKey("GuessDistance")) {
			crmOrderMap.put("planMileage", MapUtils.getString(orderMap, "GuessDistance", "0"));
		} else {
			crmOrderMap.put("planMileage", "0");
		}
		if (orderMap.containsKey("RealDistance")) {
			crmOrderMap.put("travelMileage", MapUtils.getString(orderMap, "RealDistance", "0"));
		} else {
			crmOrderMap.put("travelMileage", "0");
		}
		if (orderMap.containsKey("AdjustDistance")) {
			crmOrderMap.put("reviseMileage", MapUtils.getString(orderMap, "AdjustDistance", "0"));
		} else {
			crmOrderMap.put("reviseMileage", "0");
		}
		if (orderMap.containsKey("Comment")) {
			crmOrderMap.put("remark", MapUtils.getString(orderMap, "Comment", ""));
		} else {
			crmOrderMap.put("remark", "");
		}
		/**
		 * @Description orderMap配置字段drOrderNNo、drDiagnoseReport
		 **/
		crmOrderMap.put("drOrderNNo", "");
		crmOrderMap.put("drDiagnoseReport", "");
		/**
		 * @Description statusMap配置字段billStatus、refuseReason、actionTime、directorName、directorPhone
		 * assistEngineerName、engineerPhone、location、positionLat、positionLon、phoneIMEI
		 **/

		if (statusMap.containsKey("ProcessorId")) {
			UserT userInfo = loginDao.getUserByid(statusMap.get("ProcessorId").toString());
			if (userInfo != null) {
				crmOrderMap.put("directorName", userInfo.getContact());
				crmOrderMap.put("directorPhone", userInfo.getPhone());
			}
		}
		String orderStatus = statusMap.get("processStatus").toString();
		if (statusMap.containsKey("processStatus")) {
			crmOrderMap.put("billStatus", statusMap.get("processStatus"));
		}
		if (statusMap.containsKey("Location")) {
			crmOrderMap.put("location", statusMap.get("Location"));
		} else {
			crmOrderMap.put("location", "");
		}
		if (statusMap.containsKey("LocLon")) {
			crmOrderMap.put("positionLon", statusMap.get("LocLon"));
		} else {
			crmOrderMap.put("positionLon", 0.0);
		}
		if (statusMap.containsKey("LocLat")) {
			crmOrderMap.put("positionLat", statusMap.get("LocLat"));
		} else {
			crmOrderMap.put("positionLat", 0.0);
		}
		if (statusMap.containsKey("IMEI")) {
			crmOrderMap.put("phoneIMEI", statusMap.get("IMEI"));
		} else {
			crmOrderMap.put("phoneIMEI", "");
		}
		if (statusMap.containsKey("CreateTime")) {
			crmOrderMap.put("actionTime", statusMap.get("CreateTime"));
		} else {
			crmOrderMap.put("actionTime", "");
		}

		if (orderStatus.equals("3")) {// 区域服务经理拒单
			if (orderMap.containsKey("TransferReason")) {
				crmOrderMap.put("refuseReason", orderMap.get("TransferReason"));
			}

		} else if (orderStatus.equals("5")) {
			if (orderMap.containsKey("RefuseReasonStation")) {
				crmOrderMap.put("refuseReason", orderMap.get("RefuseReasonStation"));
			}
		} else if (orderStatus.equals("7")) {

			if (orderMap.containsKey("ID")) {
				List<Map<String, Object>> list = workOrderRePairDao
						.getServiceAssociateTechnician(orderMap.get("ID").toString());
				String assistEngineerName = "";
				String engineerPhone = "";
				if (list != null && list.size() > 0) {
					for (int i = 0; i < list.size(); i++) {
						Map<String, Object> assistMap = list.get(i);
						if (i != list.size() - 1) {
							assistEngineerName = assistEngineerName + assistMap.get("UserName") + ",";
							engineerPhone = engineerPhone + assistMap.get("Phone") + ",";
						} else {
							assistEngineerName = assistEngineerName + assistMap.get("UserName");
							engineerPhone = engineerPhone + assistMap.get("Phone");
						}

					}

				}
				crmOrderMap.put("assistEngineerName", orderMap.get("assistEngineerName"));
				crmOrderMap.put("engineerPhone", orderMap.get("engineerPhone"));
			}

		} else if (orderStatus.equals("9")) {
			if (orderMap.containsKey("RefuseReasonEngineer")) {
				crmOrderMap.put("refuseReason", orderMap.get("RefuseReasonEngineer"));
			}

		} else if (orderStatus.equals("16")) {
			if (orderMap.containsKey("CloseReason")) {
				crmOrderMap.put("refuseReason", orderMap.get("CloseReason"));
			}

		} else {
			crmOrderMap.put("refuseReason", "");
		}

		if (!crmOrderMap.containsKey("refuseReason")) {
			crmOrderMap.put("refuseReason", "");
		}
		if (!crmOrderMap.containsKey("assistEngineerName")) {
			crmOrderMap.put("assistEngineerName", "");
		}
		if (!crmOrderMap.containsKey("engineerPhone")) {
			crmOrderMap.put("engineerPhone", "");
		}

		return crmOrderMap;
	}

	/**
	 * @return java.util.Map<java.lang.String, java.lang.Object>
	 * @Author Joe
	 * @Description 将APP工单评价信息参数转化成CRM接口字段信息
	 * @Date 3:57 PM 2019/7/4
	 * @Param [map]
	 **/
	public Map<String, Object> appWorkOrderUserCommentToCrmWorkOrderData(Map<String, Object> orderMap,
																		 Map<String, Object> userCommentMap) {

		Map<String, Object> crmOrderUserCommentMap = new HashedMap<String, Object>();
		/**
		 * @Description orderMap配置字段orderNo、oldOrderNo、CRMNo、serviceCar、planMileage
		 * travelMileage、reviseMileage、remark
		 **/
		if (orderMap.containsKey("OrderNo")) {
			crmOrderUserCommentMap.put("orderNo", orderMap.get("OrderNo"));
		}

		if (orderMap.containsKey("OrderNoCrm")) {
			crmOrderUserCommentMap.put("crmNo", orderMap.get("OrderNoCrm"));
		} else {
			crmOrderUserCommentMap.put("crmNo", "");
		}
		crmOrderUserCommentMap.put("hasRepair", Integer.parseInt((String) userCommentMap.get("BackNormal")));

		int satisfaction = Integer.parseInt((String) userCommentMap.get("Satisfaction"));
		crmOrderUserCommentMap.put("isServiceSatisfied", satisfaction);
		if (satisfaction == 0) {
			crmOrderUserCommentMap.put("serviceContent", (String) userCommentMap.get("UnSatisfiedReason"));
		}
		String unSatisfiedExplain = (String) userCommentMap.get("UnSatisfiedExplain"); //不满意具体说明
		if (StringUtils.isNotBlank(unSatisfiedExplain)) {
			crmOrderUserCommentMap.put("serviceDescription", unSatisfiedExplain);
		}
		crmOrderUserCommentMap.put("isCharge", Integer.parseInt((String) userCommentMap.get("IsCharged")));

		int willShare = Integer.parseInt((String) userCommentMap.get("WillShare"));
		crmOrderUserCommentMap.put("recommendScores", (String) userCommentMap.get("WillShare"));
		if (willShare <= 6) {
			crmOrderUserCommentMap.put("recommendDescription", (String) userCommentMap.get("ShareReason"));
		}
		String shareExplain = (String) userCommentMap.get("ShareExplain"); //不愿意具体说明
		if (StringUtils.isNotBlank(shareExplain)) {
			crmOrderUserCommentMap.put("recommendReason", shareExplain);
		}

		return crmOrderUserCommentMap;
	}

	/**
	 * @return java.util.Map<java.lang.String, java.lang.Object>
	 * @Author Joe
	 * @Description 将APP工单信息参数转化成CRM接口字段信息
	 * @Date 3:57 PM 2019/7/4
	 * @Param [map]
	 **/
	public Map<String, Object> appWorkOrderToCrmWorkOrderData(Map<String, Object> map, String crmStationNo,
															  CompanyT companyInfo, UserT userInfo) {

		Map<String, Object> crmOrderMap = new HashedMap<String, Object>();
		crmOrderMap.put("orderNo", map.get("OrderNo"));
		crmOrderMap.put("ESN", map.get("ESN"));
		crmOrderMap.put("equipmentNo", map.get("VIN"));
		crmOrderMap.put("customerName", map.get("CustomerName"));
		crmOrderMap.put("customerPhone", map.get("CustomerPhone"));
		crmOrderMap.put("faultLocation", map.get("Location"));
		crmOrderMap.put("faultLat", map.get("LocLat"));
		crmOrderMap.put("faultLon", map.get("LocLon"));
		crmOrderMap.put("serviceCar", MapUtils.getString(map, "ServiceCarNo", ""));
		crmOrderMap.put("needGoOut", map.get("IsOutside"));
		crmOrderMap.put("faultDesc", map.get("CustomerComplaint"));
		crmOrderMap.put("stationNo", crmStationNo);

		if (companyInfo != null) {
			crmOrderMap.put("serviceChannel", companyInfo.getCompanyNo());
		} else {
			crmOrderMap.put("serviceChannel", "");
		}

		crmOrderMap.put("orderSource", map.get("OrderSource"));
		if (userInfo != null) {
			crmOrderMap.put("creatPerson", userInfo.getContact());
		} else {
			crmOrderMap.put("creatPerson", "");
		}
		crmOrderMap.put("creatTime", map.get("CreateTime"));
		String comment = MapUtils.getString(map, "Comment", "");
		crmOrderMap.put("remark", comment);

		return crmOrderMap;
	}

	/**
	 * 将CRM异常信息参数转化成APP table对应字段 @Title:
	 * turnCRMParamDataToAppTableData @Description:
	 * TODO(这里用一句话描述这个方法的作用) @param @param map @param @return @return
	 * Map<String,Object> @throws
	 */
	public Map<String, Object> turnCRMParamDataToAppTableData(Map<String, Object> map) {
		try {
			Map<String, Object> appMap = new HashedMap<String, Object>();
			appMap.put("APIName", map.get("interfaceName"));
			appMap.put("CompanyNo", map.get("company"));
			if (map.containsKey("data")) {
				appMap.put("Data", map.get("data").toString());
			}
			if (map.containsKey("message")) {
				appMap.put("ExceptionInfo", map.get("message").toString());
			}
			appMap.put("Flag", 0);
			appMap.put("Direction", 1);
			appMap.put("SystemTime", map.get("time"));
			return appMap;
		} catch (Exception e) {
			// TODO: handle exception
			Map<String, Object> crmMap = new HashedMap<String, Object>();
			crmMap.put("error", true);
			crmMap.put("APIName", "syncCRMExceptions");
			if (map.containsKey("company")) {
				crmMap.put("CompanyNo", map.get("company"));
			}
			if (map.containsKey("data")) {
				crmMap.put("Data", map.get("data").toString());
			}
			if (map.containsKey("ExceptionInfo")) {
				crmMap.put("ExceptionInfo", e.getMessage().toString());
			}
			crmMap.put("Direction", 0);
			crmMap.put("SystemTime", LocalTimeUtil.getRealCurrentTime());
			return crmMap;
		}
	}

	/**
	 * JSONObject to Map @Title: toHashMap @Description:
	 * TODO(这里用一句话描述这个方法的作用) @param @param jsonObject @param @return @return
	 * HashMap<String,String> @throws
	 */
	private HashMap<String, Object> toHashMap(JSONObject jsonObject) {
		HashMap<String, Object> data = new HashMap<String, Object>();
		Iterator<?> it = jsonObject.keys();
		// 遍历jsonObject数据，添加到Map对象
		while (it.hasNext()) {
			String key = String.valueOf(it.next());
			Object value = (Object) jsonObject.get(key);
			data.put(key, value);
		}
		return data;
	}

	/**
	 * @return void
	 * @Author Joe
	 * @Description //保存异常信息到APIExceptionT
	 * @Date 2:20 PM 2019/9/3
	 * @Param [interfaceName, msg, data, companyNo]
	 **/
	private void saveToAPIExceptionT(String interfaceName, String msg, String data, String companyNo) {
		APIExceptionT crmApiException = new APIExceptionT();
		crmApiException.setAPIName(interfaceName);
		crmApiException.setCompanyNo(companyNo);
		crmApiException.setData(data);
		crmApiException.setDirection(0);
		crmApiException.setExceptionInfo(msg);
		crmApiException.setFlag(0);
		crmApiException.setSystemTime(LocalTimeUtil.getRealCurrentTime());
		crmServiceDao.saveExceptionToExpTable(crmApiException);
	}

	/**
	 * @return void
	 * @Author Joe
	 * @Description //保存工单记录及发消息（CAC远程解决）
	 * @Date 5:46 PM 2019/9/9
	 * @Param [updateOrderMap, currentTime, customerUser]
	 **/
	public void saveOperationAndMessageRecords(Map<String, Object> updateOrderMap, String currentTime,
											   List<UserT> customerUser) {
		// 1、CAC远程解决
		//保存工单操作记录表
		// 1、记录用户行为日志（需要把上面保存成功的工单Id放进map中）
		workOrderTServiceImpl.saveOperation(MapUtils.getLongValue(updateOrderMap, "OrderId", 0), -1,
				MapUtils.getIntValue(updateOrderMap, "OrderStatus", 0), "CAC远程解决服务工单",
				MapUtils.getString(updateOrderMap, "LocLon", ""), MapUtils.getString(updateOrderMap, "LocLat", ""),
				MapUtils.getString(updateOrderMap, "Location", ""), "", 0, -1, currentTime);

		// 3、发送短信消息提醒
		String msg = "您的工单维修完成，工单号" + updateOrderMap.get("OrderNo") + "，请查看。";

		// 保存工单负责人为用户
		//					workOrderTServiceImpl.savePrincipal(MapUtils.getLongValue(updateOrderMap,"OrderId",0),
		//							MapUtils.getIntValue(updateOrderMap,"OrderStatus",0),
		//							1,customerUser.get(0).getId(),-1,currentTime);

		if (org.apache.commons.collections.CollectionUtils.isNotEmpty(customerUser)) {
			//调用短信接口推送短信
			SmsUtils.sendMessage(customerUser.get(0).getPhone(), msg);
			List<Map<String, Object>> notifyRecordTMapList = new ArrayList<>();
			notifyRecordTMapList
					.add(workOrderTServiceImpl.saveMsgOperation(MapUtils.getLongValue(updateOrderMap, "OrderId", 0), 10,
							5, customerUser.get(0).getId(), msg, 1, currentTime, "", -1));
			if (CollectionUtils.isNotEmpty(notifyRecordTMapList)) {
				workOrderRePairDao.saveMsgOperation(notifyRecordTMapList);
			}
			// APP推送
			noticeService.push(10, 5, MapUtils.getLong(updateOrderMap, "OrderId", 0L), customerUser.get(0).getId(),
					customerUser.get(0).getUserName(), "工单维修完成", msg, msg, 0L);
		}
	}

	/**
	 * @return void
	 * @Author Joe
	 * @Description 同步工单状态到CRM系统
	 * @Date 5:54 PM 2019/9/9
	 * @Param [updateOrderMap, currentTime, customerUser, company]
	 **/
	public void sendInterfaceMessageToCRM(Map<String, Object> updateOrderMap, String currentTime,
										  List<UserT> customerUser, String company) {

		//调用2.2.3 APP系统同步工单状态信息到CRM系统
		Map<String, Object> parameters = new HashMap<>();
		parameters.put("orderNo", updateOrderMap.get("OrderNo"));
		parameters.put("CRMNo", updateOrderMap.get("OrderNoCrm"));
		parameters.put("billStatus", updateOrderMap.get("OrderStatus"));
		parameters.put("stationNo", "");
		parameters.put("refuseReason", "");
		parameters.put("timeOutReason", "");
		parameters.put("lackOfPart", new ArrayList<>());
		parameters.put("actionTime", currentTime);
		parameters.put("directorName", "APP系统");
		parameters.put("directorPhone", "18501075230");
		parameters.put("planMileage", "");
		parameters.put("travelMileage", "");
		parameters.put("serviceCar", "");
		parameters.put("positionLat", 0);
		parameters.put("positionLon", 0);
		parameters.put("drOrderNo", "");
		parameters.put("drDiagnoseReport", "");
		//当服务工单状态为待用户评价时     把诊断工单id和诊断工单web页面地址传给页面
		if (org.apache.commons.collections.CollectionUtils.isNotEmpty(customerUser)) {
			parameters.put("appAppraise", 1);
		} else {
			parameters.put("appAppraise", 0);
		}
		try {
			CRMResponeEntity crmResponeEntity = CRMApiUtils.getCRMServiceApi().syncOrderStatusToCrm(company,
					crmServiceDao, redisClientUtils, parameters,null);
			if (crmResponeEntity.getStatus() != 0) {
				LOG.error("同步工单状态至CRM失败!状态:" + crmResponeEntity.getStatus() + ",错误信息:" + crmResponeEntity.getMessage());
			}
		} catch (Exception e) {
			e.printStackTrace();
			LOG.error("同步工单状态至CRM失败!错误信息:" + e.getMessage(), e);
		}

	}

	public static enum SSRepairOperation {
		SAVE, UPDATE;
	}

	/**
	 * @return void
	 * @Author Joe
	 * @Description 取下工单/关闭工单 发送消息
	 * @Date 5:27 PM 2019/9/25
	 * @Param [map, status]
	 **/
	private void saveOperationAndMessageRecordsWithCloseAction(Map<String, Object> updateOrderMap, int status) {
		if (status == 1) {
			String currentTime = LocalTimeUtil.getRealCurrentTime();
			workOrderTServiceImpl.saveOperation(Long.parseLong(updateOrderMap.get("OrderId").toString()), -1,
					Integer.parseInt(updateOrderMap.get("OrderStatus").toString()), "CAC取消工单", "0.00", "0.00", "", "",
					0, -1, currentTime);
			// 3、发送短信消息提醒
			String msg = "您有工单取消，工单号" + updateOrderMap.get("OrderNo") + "，请查看。";
			String customerPhone = MapUtils.getString(updateOrderMap, "CustomerPhone", "");
			List<UserT> customerUser = loginDao.getUserByPhone(customerPhone);

			// 保存工单负责人为用户
			//					workOrderTServiceImpl.savePrincipal(MapUtils.getLongValue(updateOrderMap,"OrderId",0),
			//							MapUtils.getIntValue(updateOrderMap,"OrderStatus",0),
			//							1,customerUser.get(0).getId(),-1,currentTime);

			if (org.apache.commons.collections.CollectionUtils.isNotEmpty(customerUser)) {
				//调用短信接口推送短信
				SmsUtils.sendMessage(customerUser.get(0).getPhone(), msg);
				List<Map<String, Object>> notifyRecordTMapList = new ArrayList<>();
				notifyRecordTMapList
						.add(workOrderTServiceImpl.saveMsgOperation(MapUtils.getLongValue(updateOrderMap, "OrderId", 0),
								10, 5, customerUser.get(0).getId(), msg, 1, currentTime, "", -1));
				if (CollectionUtils.isNotEmpty(notifyRecordTMapList)) {
					workOrderRePairDao.saveMsgOperation(notifyRecordTMapList);
				}

				// APP推送
				noticeService.push(10, 5, MapUtils.getLong(updateOrderMap, "OrderId", 0L), customerUser.get(0).getId(),
						customerUser.get(0).getUserName(), "工单已取消", msg, msg, 0L);
			}
		} else {

			// 更新工单负责人表、信息提醒
			String smstext = "";
			String smsTipText = "";
			updateOrderMap.put("ServiceStationID", updateOrderMap.get("ServiceStationId"));

			{
				String currentTime = LocalTimeUtil.getRealCurrentTime();
				// 1、保存工单操作记录表
				workOrderTServiceImpl.saveOperation(Long.parseLong(updateOrderMap.get("OrderId").toString()), -1,
						Integer.parseInt(updateOrderMap.get("OrderStatus").toString()), "CAC关闭工单", "0.00", "0.00", "",
						"", 0, -1, LocalTimeUtil.getRealCurrentTime());

				smstext = "您有工单被关闭，工单号" + updateOrderMap.get("OrderNo") + "，请查看。";
				smsTipText = "工单关闭提醒";
				List<UserT> userTS = userTDao.getUserTByServiceStationId(updateOrderMap);
				if (CollectionUtils.isNotEmpty(userTS)) {
					for (UserT userZZ : userTS) {
						if (userZZ != null) {
							// 3、发送短信消息提醒
							SmsUtils.sendMessage(userZZ.getPhone(), smstext);
							List<Map<String, Object>> notifyRecordTMapList = new ArrayList<>();
							notifyRecordTMapList.add(workOrderTServiceImpl.saveMsgOperation(
									Long.parseLong(updateOrderMap.get("OrderId").toString()), 20, 1, userZZ.getId(),
									smstext, 1, currentTime, "", -1));
							if (CollectionUtils.isNotEmpty(notifyRecordTMapList)) {
								workOrderRePairDao.saveMsgOperation(notifyRecordTMapList);
							}

							// APP推送
							noticeService.push(20, 1, MapUtils.getLong(updateOrderMap, "OrderId", 0L), userZZ.getId(),
									userZZ.getUserName(), smsTipText, smstext, smstext, 0L);
						}
					}
				}
				List<UserT> xXYUserTS = userTDao.getMsgUserTByServiceStationId(updateOrderMap);
				if (CollectionUtils.isNotEmpty(xXYUserTS)) {
					for (UserT userXXY : xXYUserTS) {
						if (userXXY != null) {
							// 3、发送短信消息提醒
							SmsUtils.sendMessage(userXXY.getPhone(), smstext);
							noticeService.push(20, 1, MapUtils.getLong(updateOrderMap, "OrderId"), userXXY.getId(),
									userXXY.getUserName(), null, smstext, null, 0L);
							// 5、保存通知消息记录
							List<Map<String, Object>> notifyRecordTMapList = new ArrayList<>();
							notifyRecordTMapList.add(workOrderTServiceImpl.saveMsgOperation(
									Long.parseLong(updateOrderMap.get("OrderId").toString()), 20, 1, userXXY.getId(),
									smstext, 1, currentTime, "", -1));
							if (CollectionUtils.isNotEmpty(notifyRecordTMapList)) {
								workOrderRePairDao.saveMsgOperation(notifyRecordTMapList);
							}
						}
					}
				}

			}
		}
	}


	//ljk     dbu渠道crm通过或者驳回异常关闭申请   异常关闭服务工单
	@Override
	@Transactional
	public ModelAndView syncWOCloseRequest(Map<String, Object> httpMap) {
		HttpServletRequest request = (HttpServletRequest) httpMap.get("request");
		HttpServletResponse response = (HttpServletResponse) httpMap.get("response");
		/**
		 * 1、将CRM请求参数转化成APP系统请求参数s
		 */
		@SuppressWarnings("unchecked")
		Map<String, Object> requestMap = (Map<String, Object>) JSONObject
				.fromObject(httpMap.get(CRMServiceConst.CRM_REQUEST_PARAMS).toString());

        String company = httpMap.get(CRMServiceConst.CRM_REQUEST_COMPANY).toString();
        JSONObject jObject = new JSONObject();


		if (company.equals(CRMServiceConst.DBU)) {
			String orderNo = MapUtils.getString(requestMap, "orderNo", "");
			//1:异常关闭工单    2:通过和驳回异常关闭申请
			int type = MapUtils.getIntValue(requestMap, "type", -1);
			//0:拒绝异常关单    1:同意异常关单
			int isClosed = MapUtils.getIntValue(requestMap, "isClosed", -1);
			if (StringUtils.isEmpty(orderNo) || type == -1 || isClosed == -1) {
				jObject.put("status", 1);
				jObject.put("msg", "缺少必要参数！");
				jObject.put("data", new JSONObject());
				// 返回客户
				ParameterTool.writeResponse(response, jObject.toString());
				jObject = null;
				return null;
			}

			Map<String, Object> orderInfoMap = workOrderTDao.getOrderByNo(orderNo);
			if (MapUtils.isEmpty(orderInfoMap)) {
				jObject.put("status", 1);
				jObject.put("msg", "未查询到工单！");
				jObject.put("data", new JSONObject());
				// 返回客户
				ParameterTool.writeResponse(response, jObject.toString());
				jObject = null;
				return null;
			}
			if ((type != 1 && type != 2) || (isClosed != 0 && isClosed != 1)) {
				jObject.put("status", 1);
				jObject.put("msg", "所传参数值不在范围内！");
				jObject.put("data", new JSONObject());
				// 返回客户
				ParameterTool.writeResponse(response, jObject.toString());
				jObject = null;
				return null;
			}
			String currentTime = LocalTimeUtil.getRealCurrentTime(); //获取当前时间
			long orderId = MapUtils.getLongValue(orderInfoMap, "ID", 0);
			String oldUpdateTime = MapUtils.getString(orderInfoMap, "UpdateTime", "");
			String serviceSubtype = MapUtils.getString(orderInfoMap, "ServiceSubtype", "");
			String sellType = MapUtils.getString(orderInfoMap, "SellType", "");
			if (type == 1) {   //crm直接异常关闭服务工单  修改工单状态   插入操作记录表
				Map<String, Object> closeOrderMsgMap = new HashMap<>();
				closeOrderMsgMap.put("OrderStatus", 16);
				closeOrderMsgMap.put("CloseTime", currentTime);
				closeOrderMsgMap.put("CloseReason", "crm异常关闭");
				closeOrderMsgMap.put("Updator", -1);
				closeOrderMsgMap.put("UpdateTime", currentTime);
				closeOrderMsgMap.put("ID", orderId);
				closeOrderMsgMap.put("OldUpdateTime", oldUpdateTime);
				workOrderTDao.updateCloseWorkOrderById(closeOrderMsgMap);
				workOrderTServiceImpl.saveOperation(orderId, -1,
						16, "crm异常关闭", "0.00", "0.00", "", "", 0, -1,
						currentTime);
				//DBU渠道关闭工单需要调用关闭主动升级工单接口
				//1: 服务工单异常关闭
				//2: 服务工单已取消
				//3: 服务工单已完成
				escalationService.disableEscalationByWorkOrderId(orderId, 1);
				//修改campaign任务状态
				updateCampaignStatus(orderId,5,-1L,"crm直接异常关闭服务工单");
			} else if (type == 2) {    //app发起异常关闭申请    crm审核通过或者审核不通过
				//获取该工单服务站站长和信息员
				List<UserT> serviceStationMaster = userTDao.getStationMasterListByServiceStationId(MapUtils.getLongValue(orderInfoMap, "ServiceStationId", 0));
				//获取该工单服务站指派的技师
				Map<String, Object> mapp = new HashMap<>();
				mapp.put("serviceStationId", MapUtils.getLongValue(orderInfoMap, "ServiceStationId", 0));
				mapp.put("ID", orderId);
				//获取技师信息
				List<UserT> fWJSUserList = userTDao.getUserTByServiceStationIdWorkOrderId(mapp);
				//区域工程师信息
				Map<String, Object> qygcsMap = positionUserTDao.getDBUAreaManager(orderId);
				//获取区域工程师信息
				mapp.put("ServiceStationID", MapUtils.getLongValue(orderInfoMap, "ServiceStationId", 0));
				mapp.put("CompanyID", 1);
				List<PositionUserT> positionUserTList = positionUserTDao
						.getPostUserTListByServiceStationIdCompanyId(mapp);
				//新建消息提醒表对象list(可能会推送多人短信提醒)
				List<Map<String, Object>> notifyRecordTMapList = new ArrayList<>();

				if (isClosed == 0) {    //0:(crm审核不通过)拒绝异常关单
					//dbucrm审核不通过，拒单异常关闭逻辑
					//修改工单状态为异常关闭申请中上一个状态   保存流水表   保存负责人表为之前的负责人   推送消息
					//获取工单上一个状态的信息
					Map<String, Object> afterWorkOrderFlowMap = workOrderFlowTDao.getAfterWorkOrderFlowByOrderId(orderId, 31);
					//工单上一个状态
					if (MapUtils.isNotEmpty(afterWorkOrderFlowMap)) {
						//修改工单状态
						int afterOrderStatus = MapUtils.getIntValue(afterWorkOrderFlowMap, "processStatus", 0);
						Map<String, Object> updateOrderMap = new HashMap<>();
						updateOrderMap.put("OrderStatus", afterOrderStatus);
						updateOrderMap.put("Updator", -1);
						updateOrderMap.put("UpdateTime", currentTime);
						updateOrderMap.put("OrderId", orderId);
						updateOrderMap.put("OldUpdateTime", oldUpdateTime);
						int count = workOrderTDao.updateWorkOrderFinish(updateOrderMap);
						//插入流水表
						workOrderTServiceImpl.saveOperation(orderId, -1,
								afterOrderStatus, "crm驳回异常关闭申请", "0.00", "0.00", "", "", 0, -1,
								currentTime);
						//保存负责人表
						List<Map<String, Object>> afterWorkOrderPrincipalMapList = workOrderPrincipalTDao.getWorkOrderPrincipalListByOrderId(orderId, afterOrderStatus);
						if (CollectionUtils.isNotEmpty(afterWorkOrderPrincipalMapList)) {
							for (Map<String, Object> afterWorkOrderPrincipalMap : afterWorkOrderPrincipalMapList) {
								int IsPrincipal = MapUtils.getIntValue(afterWorkOrderPrincipalMap, "IsPrincipal", 0);
								long PrincipalId = MapUtils.getLongValue(afterWorkOrderPrincipalMap, "UserId", 0);
								workOrderTServiceImpl.savePrincipal(orderId, afterOrderStatus, IsPrincipal, PrincipalId, -1, currentTime);
							}
						}
						//发送短信和app消息     推给站长信息员技师区域工程师
						String msg = "您有工单关闭申请审核不通过，工单号：" + orderNo + "，请继续服务";
						//判断站长信息员集合是否为空，不为空推送短信app消息
						if (CollectionUtils.isNotEmpty(serviceStationMaster)) {
							for (UserT userT : serviceStationMaster) {
								String phone = userT.getPhone(); //手机号
								SmsUtils.sendMessage(phone, msg);
								Map<String, Object> FWZZNotifyRecordTMap = new HashMap<String, Object>();
								FWZZNotifyRecordTMap.put("OrderId", orderId);
								FWZZNotifyRecordTMap.put("Function", 3);
								FWZZNotifyRecordTMap.put("Category", 1);
								FWZZNotifyRecordTMap.put("ReceiverId", userT.getId()); //接收人
								FWZZNotifyRecordTMap.put("Content", msg);
								FWZZNotifyRecordTMap.put("SendType", 1); //短信推送
								FWZZNotifyRecordTMap.put("SendTime", currentTime);
								FWZZNotifyRecordTMap.put("Status", 1);
								FWZZNotifyRecordTMap.put("ExceptionInfo", "");
								FWZZNotifyRecordTMap.put("IsRead", 0);
								FWZZNotifyRecordTMap.put("Flag", 0);
								FWZZNotifyRecordTMap.put("Creator", -1);
								FWZZNotifyRecordTMap.put("CreateTime", currentTime);
								notifyRecordTMapList.add(FWZZNotifyRecordTMap);

								//推送App提醒消息
								noticeService.push(3, 1, orderId, userT.getId(), userT.getUserName(),
										"工单异常关闭申请审核不通过提醒", msg, msg, -1L);
							}
						}
						//判断指派的技师集合是否为空，不为空推送短信app消息
						if (CollectionUtils.isNotEmpty(fWJSUserList)) {
							for (UserT userT : fWJSUserList) {
								if (userT != null) {
									if (userT.getIsPrincipal() == 1) {
										String FFJSphone = userT.getPhone(); //服务技师手机号
										SmsUtils.sendMessage(FFJSphone, msg);
										Map<String, Object> FFJSNotifyRecordTMap = new HashMap<String, Object>();
										FFJSNotifyRecordTMap.put("OrderId", orderId);
										FFJSNotifyRecordTMap.put("Function", 3);
										FFJSNotifyRecordTMap.put("Category", 1);
										FFJSNotifyRecordTMap.put("ReceiverId", userT.getId()); //接收人
										FFJSNotifyRecordTMap.put("Content", msg);
										FFJSNotifyRecordTMap.put("SendType", 1);
										FFJSNotifyRecordTMap.put("SendTime", currentTime);
										FFJSNotifyRecordTMap.put("Status", 1);
										FFJSNotifyRecordTMap.put("ExceptionInfo", "");
										FFJSNotifyRecordTMap.put("IsRead", 0);
										FFJSNotifyRecordTMap.put("Flag", 0);
										FFJSNotifyRecordTMap.put("Creator", -1);
										FFJSNotifyRecordTMap.put("CreateTime", currentTime);
										notifyRecordTMapList.add(FFJSNotifyRecordTMap);
										//推送App提醒消息
										noticeService.push(3, 1, orderId, userT.getId(), userT.getUserName(),
												"工单异常关闭申请审核不通过提醒", msg, msg, -1L);
									}
								}
							}
						}
						//判断区域工程师集合是否为空，不为空推送短信和app消息
						if (CollectionUtils.isNotEmpty(positionUserTList)) {
							for (PositionUserT positionUserT : positionUserTList) {
								String QYFWJLphone = positionUserT.getUserPhone(); //区域服务经理手机号
								//拿dbu指定的区域工程师手机号和上面的区域工程师集合循环比较，比较到了则推送，其他渠道工单不走此逻辑
								if (MapUtils.isNotEmpty(qygcsMap) && !(MapUtils.getString(qygcsMap, "DBEngineerPhone", "")
										.equals(positionUserT.getUserPhone()))) {
									continue;
								}
								SmsUtils.sendMessage(QYFWJLphone, msg);
								List<UserT> qyfwjlList = loginDao.getUserByPhone(QYFWJLphone);
								Map<String, Object> FWJLNotifyRecordTMap = new HashMap<String, Object>();
								FWJLNotifyRecordTMap.put("OrderId", orderId);
								FWJLNotifyRecordTMap.put("Function", 3);
								FWJLNotifyRecordTMap.put("Category", 1);
								if (CollectionUtils.isNotEmpty(qyfwjlList)) {
									FWJLNotifyRecordTMap.put("ReceiverId", qyfwjlList.get(0).getId()); //接收人
									FWJLNotifyRecordTMap.put("ExceptionInfo", "");
								} else {
									FWJLNotifyRecordTMap.put("ReceiverId", 0); //接收人
									FWJLNotifyRecordTMap.put("ExceptionInfo", "未查询到该用户");
								}
								FWJLNotifyRecordTMap.put("Content", msg);
								FWJLNotifyRecordTMap.put("SendType", 1);
								FWJLNotifyRecordTMap.put("SendTime", currentTime);
								FWJLNotifyRecordTMap.put("Status", 1);
								FWJLNotifyRecordTMap.put("IsRead", 0);
								FWJLNotifyRecordTMap.put("Flag", 0);
								FWJLNotifyRecordTMap.put("Creator", -1);
								FWJLNotifyRecordTMap.put("CreateTime", currentTime);
								notifyRecordTMapList.add(FWJLNotifyRecordTMap);
								//推送App提醒消息
								if (CollectionUtils.isNotEmpty(qyfwjlList)) {
									UserT qyfwjl = qyfwjlList.get(0);
									noticeService.push(10, 5, orderId, qyfwjl.getId(), qyfwjl.getUserName(),
											"工单异常关闭申请审核不通过提醒", msg, msg, -1L);
								}
							}
						}


					}

				} else if (isClosed == 1) {   //1:(crm审核通过)同意异常关单
					int orderStatus = 16;
					//dbucrm审核通过，同意异常关闭工单逻辑
					//修改工单状态为异常关闭   保存流水表    无负责人   推送消息
					CloseWorkOrderCondition closeWorkOrderCondition = new CloseWorkOrderCondition();
					closeWorkOrderCondition.setStatus(orderStatus);
					closeWorkOrderCondition.setUpdateTime(currentTime);
					closeWorkOrderCondition.setUpdator(-1L);
					closeWorkOrderCondition.setId(orderId);
					//修改工单状态
					workOrderTDao.updateWorkOrderStatusById(closeWorkOrderCondition);
					//保存流水
					workOrderTServiceImpl.saveOperation(orderId, -1, 16, MapUtils.getString(orderInfoMap, "CloseReason", "crm异常关闭"),
							"0.00", "0.00", "", "", 0, -1, currentTime);
					//推送消息
					String msg = "您有工单关闭申请审核通过，工单编号：" + orderNo + "，属于\"" + sellType + "\"" + (StringUtils.isNotBlank(serviceSubtype) ? "-" + serviceSubtype : "") + "，工单结束，请查看";
					String yhMsg = "您有工单因" + MapUtils.getString(orderInfoMap, "CloseReason", "crm异常关闭") + "原因异常关闭，工单号" + orderNo + "，属于\"" + sellType + "\"" + (StringUtils.isNotBlank(serviceSubtype) ? "-" + serviceSubtype : "") + "，工单结束";
					//判断站长信息员集合是否为空，不为空推送短信app消息
					if (CollectionUtils.isNotEmpty(serviceStationMaster)) {
						for (UserT userT : serviceStationMaster) {
							String phone = userT.getPhone(); //手机号
							SmsUtils.sendMessage(phone, msg);
							Map<String, Object> FWZZNotifyRecordTMap = new HashMap<String, Object>();
							FWZZNotifyRecordTMap.put("OrderId", orderId);
							FWZZNotifyRecordTMap.put("Function", 10); //工单异常关闭提醒
							FWZZNotifyRecordTMap.put("Category", 5); //工单异常关闭提醒
							FWZZNotifyRecordTMap.put("ReceiverId", userT.getId()); //接收人
							FWZZNotifyRecordTMap.put("Content", msg);
							FWZZNotifyRecordTMap.put("SendType", 1); //短信推送
							FWZZNotifyRecordTMap.put("SendTime", currentTime);
							FWZZNotifyRecordTMap.put("Status", 1);
							FWZZNotifyRecordTMap.put("ExceptionInfo", "");
							FWZZNotifyRecordTMap.put("IsRead", 0);
							FWZZNotifyRecordTMap.put("Flag", 0);
							FWZZNotifyRecordTMap.put("Creator", -1);
							FWZZNotifyRecordTMap.put("CreateTime", currentTime);
							notifyRecordTMapList.add(FWZZNotifyRecordTMap);

							//推送App提醒消息
							noticeService.push(10, 5, orderId, userT.getId(), userT.getUserName(),
									"工单异常关闭提醒", msg, msg, -1L);
						}
					}
					//判断指派的技师集合是否为空，不为空推送短信app消息
					if (CollectionUtils.isNotEmpty(fWJSUserList)) {
						for (UserT userT : fWJSUserList) {
							if (userT != null) {
								if (userT.getIsPrincipal() == 1) {
									String FFJSphone = userT.getPhone(); //服务技师手机号
									SmsUtils.sendMessage(FFJSphone, msg);
									Map<String, Object> FFJSNotifyRecordTMap = new HashMap<String, Object>();
									FFJSNotifyRecordTMap.put("OrderId", orderId);
									FFJSNotifyRecordTMap.put("Function", 10); //工单异常关闭提醒
									FFJSNotifyRecordTMap.put("Category", 5); //工单异常关闭提醒
									FFJSNotifyRecordTMap.put("ReceiverId", userT.getId()); //接收人
									FFJSNotifyRecordTMap.put("Content", msg);
									FFJSNotifyRecordTMap.put("SendType", 1);
									FFJSNotifyRecordTMap.put("SendTime", currentTime);
									FFJSNotifyRecordTMap.put("Status", 1);
									FFJSNotifyRecordTMap.put("ExceptionInfo", "");
									FFJSNotifyRecordTMap.put("IsRead", 0);
									FFJSNotifyRecordTMap.put("Flag", 0);
									FFJSNotifyRecordTMap.put("Creator", -1);
									FFJSNotifyRecordTMap.put("CreateTime", currentTime);
									notifyRecordTMapList.add(FFJSNotifyRecordTMap);
									//推送App提醒消息
									noticeService.push(10, 5, orderId, userT.getId(), userT.getUserName(),
											"工单异常关闭提醒", msg, msg, -1L);
								}
							}
						}
					}
					//判断区域工程师集合是否为空，不为空推送短信和app消息
					if (CollectionUtils.isNotEmpty(positionUserTList)) {
						for (PositionUserT positionUserT : positionUserTList) {
							String QYFWJLphone = positionUserT.getUserPhone(); //区域服务经理手机号
							//拿dbu指定的区域工程师手机号和上面的区域工程师集合循环比较，比较到了则推送，其他渠道工单不走此逻辑
							if (MapUtils.isNotEmpty(qygcsMap) && !(MapUtils.getString(qygcsMap, "DBEngineerPhone", "")
									.equals(positionUserT.getUserPhone()))) {
								continue;
							}
							SmsUtils.sendMessage(QYFWJLphone, msg);
							List<UserT> qyfwjlList = loginDao.getUserByPhone(QYFWJLphone);
							Map<String, Object> FWJLNotifyRecordTMap = new HashMap<String, Object>();
							FWJLNotifyRecordTMap.put("OrderId", orderId);
							FWJLNotifyRecordTMap.put("Function", 10); //工单异常关闭提醒
							FWJLNotifyRecordTMap.put("Category", 5); //工单异常关闭提醒
							if (CollectionUtils.isNotEmpty(qyfwjlList)) {
								FWJLNotifyRecordTMap.put("ReceiverId", qyfwjlList.get(0).getId()); //接收人
								FWJLNotifyRecordTMap.put("ExceptionInfo", "");
							} else {
								FWJLNotifyRecordTMap.put("ReceiverId", 0); //接收人
								FWJLNotifyRecordTMap.put("ExceptionInfo", "未查询到该用户");
							}
							FWJLNotifyRecordTMap.put("Content", msg);
							FWJLNotifyRecordTMap.put("SendType", 1);
							FWJLNotifyRecordTMap.put("SendTime", currentTime);
							FWJLNotifyRecordTMap.put("Status", 1);
							FWJLNotifyRecordTMap.put("IsRead", 0);
							FWJLNotifyRecordTMap.put("Flag", 0);
							FWJLNotifyRecordTMap.put("Creator", -1);
							FWJLNotifyRecordTMap.put("CreateTime", currentTime);
							notifyRecordTMapList.add(FWJLNotifyRecordTMap);
							//推送App提醒消息
							if (CollectionUtils.isNotEmpty(qyfwjlList)) {
								UserT qyfwjl = qyfwjlList.get(0);
								noticeService.push(10, 5, orderId, qyfwjl.getId(), qyfwjl.getUserName(),
										"工单异常关闭提醒", msg, msg, -1L);
							}
						}
					}

					String YHphone = MapUtils.getString(orderInfoMap, "CustomerPhone", ""); //用户手机号

					/**
					 * 2.10.0服务工单异常关闭暂停了对用户的消息推送，但推送记录仍需要保存
					 */
					//SmsTool.sendSms(YHphone, yhMsg);

					//先判断用户手机号是否在app中注册过，如果有拿出用户id
					List<UserT> userTs = loginDao.getUserByPhone(YHphone);
					Map<String, Object> userNotifyRecordTMap = new HashMap<String, Object>();
					userNotifyRecordTMap.put("OrderId", orderId);
					userNotifyRecordTMap.put("Function", 10); //工单异常关闭提醒
					userNotifyRecordTMap.put("Category", 5); //工单异常关闭提醒
					if (CollectionUtils.isNotEmpty(userTs)) {
						userNotifyRecordTMap.put("ReceiverId", userTs.get(0).getId()); //接收人
						userNotifyRecordTMap.put("ExceptionInfo", "");
					} else {
						userNotifyRecordTMap.put("ReceiverId", 0); //接收人
						userNotifyRecordTMap.put("ExceptionInfo", "未查询到该用户");
					}
					userNotifyRecordTMap.put("Content", yhMsg);
					userNotifyRecordTMap.put("SendType", 1);
					userNotifyRecordTMap.put("SendTime", currentTime);
					userNotifyRecordTMap.put("Status", 1);
					userNotifyRecordTMap.put("IsRead", 0);
					userNotifyRecordTMap.put("Flag", 0);
					userNotifyRecordTMap.put("Creator", -1);
					userNotifyRecordTMap.put("CreateTime", currentTime);
					notifyRecordTMapList.add(userNotifyRecordTMap);

					/**
					 * 2.10.0服务工单异常关闭暂停了对用户的消息推送，但推送记录仍需要保存
					 */
					//推送App提醒消息
					if (CollectionUtils.isNotEmpty(userTs)) {
						noticeService.pushUser(10, 5, orderId, userTs.get(0).getId(),
								userTs.get(0).getUserName(), "工单异常关闭提醒", yhMsg, yhMsg, -1L);
					}


					if (CollectionUtils.isNotEmpty(notifyRecordTMapList)) {
						workOrderRepairDao.saveMsgOperation(notifyRecordTMapList); //插入并保存消息提醒数据
					}

					//dbu的工单需要推送公众号消息   dbu微信公众号查看工单详情url
                    /*long orderChannel = MapUtils.getLongValue(orderInfoMap, "OrderChannel", 0);
                    if (orderChannel == 1) {
                        String dbuWechatWorkOrderInfoUrl = propertiesUtils.getPropertiesValue("DBUWechatWorkOrderInfoUrl");
                        Map<String, Object> orderFlowMsgMap = workOrderFlowTDao.getOrderFlowMsgById(orderId);
                        String closeReason = MapUtils.getString(orderFlowMsgMap, "CloseReason", "");
                        String closeName = MapUtils.getString(orderFlowMsgMap, "Contact", "");
                        //拼公众号中查看详情的url
                        String urlFormat = String.format(dbuWechatWorkOrderInfoUrl, orderId);
                        //推送微信公众号消息
                        String firstData = "您有一条重要的工单状态信息";
                        String keyWord1 = "编号：" + orderNo;
                        String keyWord2 = "您有工单被异常关闭，异常关闭原因" + closeReason + "，请查看！";
                        String keyWord3 = Dictionaries.OrderStatus_16.getName();
                        String keyWord4 = closeName;
                        String remark = "请点击详情查看工单内容";
                        try {
                            iOrderPushMessageService.sendOrderMessage(orderId, urlFormat, firstData, keyWord1,
                                    keyWord2, keyWord3, keyWord4, remark);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }*/

					//DBU渠道关闭工单需要调用关闭主动升级工单接口
					//1: 服务工单异常关闭
					//2: 服务工单已取消
					//3: 服务工单已完成
					escalationService.disableEscalationByWorkOrderId(orderId, 1);
					//修改campaign任务状态
					updateCampaignStatus(orderId,5,-1L,"crm同意异常关闭申请");
				}

			}
			jObject.put("status", 0);
			jObject.put("msg", "success");
			jObject.put("data", new JSONObject());
			// 返回客户
			ParameterTool.writeResponse(response, jObject.toString());
			jObject = null;

		}
		return null;
	}

	private static final JSONObject EMP_OBJ = new JSONObject();

	/**
	 * 根据服务工单编号同步服务工单服务子类型
	 */
	@Override
	@Transactional
	public void crmSyncServiceSubType(Map<String, Object> httpMap) {

		HttpServletResponse response = (HttpServletResponse) httpMap.get("response");

		@SuppressWarnings("unchecked")
		Map<String, Object> requestMap = (Map<String, Object>) JSONObject
				.fromObject(httpMap.get(CRMServiceConst.CRM_REQUEST_PARAMS).toString());

		if(validateParams(requestMap, response)) {
			requestMap.put("updateTime", LocalTimeUtil.getRealCurrentTime());

			int count = workOrderTDao.updateServiceSubtypeByOrderNo(requestMap);
			JSONObject jObject = new JSONObject();
			if (count <= 0) {
				jObject.put("status", 1);
				jObject.put("msg", "修改失败，服务工单编号可能不存在");
				jObject.put("data", EMP_OBJ);
				// 返回客户
				ParameterTool.writeResponse(response, jObject.toString());
			} else {
				jObject.put("status", 0);
				jObject.put("msg", "成功");
				jObject.put("data", EMP_OBJ);
				// 返回客户
				ParameterTool.writeResponse(response, jObject.toString());
			}
		}
	}


	/**
	 * 校验CRM传来的参数是否有问题
	 *
	 * @param requestMap
	 * @param response
	 * @return
	 */
	private boolean validateParams(Map<String, Object> requestMap, HttpServletResponse response) {

		LOG.info(String.format("同步工单服务子类型 参数httpMap: %s", requestMap));

		Object orderNo = requestMap.get("orderNo");
		String serviceSubtype = (String) requestMap.get("serviceSubtype");

		JSONObject jObject = new JSONObject();
		if (Objects.isNull(orderNo) || StringUtils.isBlank(orderNo.toString())) {
			jObject.put("status", 1);
			jObject.put("msg", "参数orderNo不能为空");
			jObject.put("data", EMP_OBJ);
			// 返回客户
			ParameterTool.writeResponse(response, jObject.toString());
			LOG.error("参数orderNo不能为空");
			return false;
		}

		requestMap.put("serviceSubtype", MapUtils.getString(requestMap, "serviceSubtype", ""));
		requestMap.put("unifiedRepairNo", MapUtils.getString(requestMap, "unifiedRepairNo", ""));

		// 2.9.0需求，crm修改服务子类型的时候并不会携带故障码、故障症状字段。
		// 如果服务子类型包含故障维修时不会清除WorkOrder_T表里的故障码、故障症状字段，否则会清除故障码、故障症状字段。
		if (StringUtils.isBlank(serviceSubtype) || !serviceSubtype.contains("故障维修")) {
			requestMap.put("faultCodes", "");
			requestMap.put("symptomName", "");
		}

		return true;
	}


	@Override
	@Transactional
	public void crmCallAPPSendSMS(Map<String, Object> map) {
		LOG.info("来自CRM的短信参数：" + map);
		HttpServletResponse response = (HttpServletResponse) map.get("response");

		@SuppressWarnings("unchecked")
		Map<String, Object> paramsMap = (Map<String, Object>) JSONObject
				.fromObject(map.get(CRMServiceConst.CRM_REQUEST_PARAMS).toString());
		String company = map.get(CRMServiceConst.CRM_REQUEST_COMPANY).toString();
		/**
		 * {
		 *	 "caseNo": "XXXX",
		 *	 "customerName": "林健坤",
		 *   "customerPhone": "11111111111",
		 *   "systemTime": "2021-03-23 00:00:00"
		 *    }
		 */
		String crmOrderNo = MapUtils.getString(paramsMap, "caseNo");
		String phone = MapUtils.getString(paramsMap, "customerPhone");
		String customerName = MapUtils.getString(paramsMap, "customerName");

		if (StringUtils.isEmpty(crmOrderNo) || StringUtils.isEmpty(phone) || StringUtils.isEmpty(customerName)) {
			ParameterTool.writeResponse(response, -1, "caseNo、customerPhone、customerName不能为空");
			return;
		}

		String tempToken = TokenUtils.getTempToken();
		String smsLink = weChatNoticeService.getSmsLinkMessageByCrm(crmOrderNo, tempToken);

		// "00"：发送成功   其它：失败
		String sendStatus = SmsUtils.sendMessage(phone, smsLink);
		String currentTime = LocalTimeUtil.getRealCurrentTime();

		CRMSendSMSMsg msg = new CRMSendSMSMsg();
		long companyId = 1;
		if (StringUtils.isNotEmpty(company) && (CompanyEnum.CCI.getCompanyNo()).equals(company)) {
			companyId = 1;
		}
		msg.setCompanyId(companyId);
		msg.setCrmOrderNo(crmOrderNo);
		msg.setCustomerName(customerName);
		msg.setCustomerPhone(phone);
		msg.setIsHaveWorkOrder(0);
		msg.setSendType(1);
		msg.setSendTime(currentTime);
		// 是否推送成功   0:失败   1:成功
		msg.setStatus("00".equals(sendStatus) ? 1 : 0);
		msg.setVersion(0);
		msg.setFlag(0);
		msg.setContent(smsLink);
		msg.setCreator(-1L);
		msg.setCreateTime(currentTime);
		crmSendSMSMsgDao.insertSelective(msg);

		JSONObject jObject = new JSONObject();
		if ("00".equals(sendStatus)) {

			//获取链接过期时间
			Integer linkTime = Integer.parseInt(propertiesUtils.getPropertiesValue("redisSmsLinkCacheTime"));
			String realExpireTime = LocalTimeUtil.getRealExpireTime(linkTime.longValue());

			// 短信发送成功时，保存短信的token信息
			WeChatSmsLinkTokenT linkToken = new WeChatSmsLinkTokenT();
			linkToken.setCompanyId(companyId);
			linkToken.setCrmOrderNo(crmOrderNo);
			linkToken.setExpireTime(realExpireTime);
			linkToken.setToken(tempToken);
			linkToken.setType(1);
			linkToken.setCreator(-1L);
			linkToken.setCreateTime(currentTime);
			weChatSmsLinkTokenTDao.insert(linkToken);

			jObject.put("status", 0);
			jObject.put("msg", "短信发送成功");
			// 返回客户
			ParameterTool.writeResponse(response, jObject.toString());
			return;
		}
		jObject.put("status", -1);
		jObject.put("msg", "短信发送失败");
		// 返回客户
		ParameterTool.writeResponse(response, jObject.toString());
	}


	/**
	 * DBU渠道
	 * 400坐席 400主管取消服务工单
	 */
	@Override
	@Transactional
	public void crmCallAPPCancelWO(Map<String, Object> map) {
		LOG.info("来自CRM的取消服务工单参数：" + map);
		HttpServletResponse response = (HttpServletResponse) map.get("response");

		@SuppressWarnings("unchecked")
		Map<String, Object> paramsMap = (Map<String, Object>) JSONObject
				.fromObject(map.get(CRMServiceConst.CRM_REQUEST_PARAMS).toString());

		String orderNo = MapUtils.getString(paramsMap, "orderNo");
		String cancelCause = MapUtils.getString(paramsMap, "cancelCause");

		// 校验参数是否为空
		if (StringUtils.isEmpty(orderNo)) {
			LOG.error("orderNo不能为空");
			ParameterTool.writeResponse(response, 1, "orderNo不能为空");
			return;
		}

		// 根据服务工单编号查询出对应的服务工单
		Map<String, Object> orderInfoMap = crmServiceDao.getOldOrderInfoByOrderNo(orderNo);
		if (orderInfoMap == null) {
			LOG.error(String.format("不存在编号:%s的服务工单", orderNo));
			ParameterTool.writeResponse(response, 1, "服务工单不存在");
			return;
		}

		/**
		 * 第一步 强制修改服务工单的状态为CAC取消
		 */
		LOG.info("第一步 强制修改服务工单的状态为CAC取消");
		Long orderId = MapUtils.getLong(orderInfoMap, "ID");

		// 根需求确认当crm取消服务工单时，系统只需要强制取消工单不需要校验状态
		CloseWorkOrderCondition condition = new CloseWorkOrderCondition();
		condition.setId(orderId);
		condition.setStatus(22);
		condition.setUpdator(-1L);
		condition.setUpdateTime(LocalTimeUtil.getRealCurrentTime());
		// 更新工单为CAC取消状态
		workOrderTDao.updateWorkOrderStatusById(condition);

		/**
		 * 第二步 关闭主动升级工单
		 */
		LOG.info("第二步 关闭主动升级工单");
		escalationService.disableEscalationByWorkOrderId(orderId, 2);

		/**
		 * 第三步 生成工单操作流水
		 */
		LOG.info("第三步 生成工单操作流水");
		workOrderTServiceImpl.doSaveOperation(orderId, -1, 22, "400坐席、主管取消工单", "0.00", "0.00", "", "", 0, -1, LocalTimeUtil.getRealCurrentTime(), cancelCause);

		/**
		 * 第四步 消息推送
		 */
		LOG.info("第四步 消息推送");
		// 消息推送失败但不应该让主业务失败
		try {
			Long customerId = MapUtils.getLong(orderInfoMap, "CustomerId");
			Long serviceStationId = MapUtils.getLong(orderInfoMap, "ServiceStationId");
			String customerPhone = MapUtils.getString(orderInfoMap, "CustomerPhone");
			sendMessage(orderId, orderNo, customerId, customerPhone, serviceStationId);
		} catch (Exception e) {
			LOG.error("<400取消推送消息失败了>" + e.getMessage());
		}


		ParameterTool.writeSuccessResponse(response);
	}

	@Override
	public void ddcrCancelStationAuthorization(Map<String, Object> map) {
		LOG.info("来自DDCR取消服务站授权参数：" + map);
		//DDCR发起取消经销商授权，若是单渠道授权的经销商，则将经销商名下所有用户置为终端用户，
		// 若是多渠道授权，则作废该渠道的授权关系
		HttpServletResponse response = (HttpServletResponse) map.get("response");

		@SuppressWarnings("unchecked")
		Map<String, Object> paramsMap = (Map<String, Object>) JSONObject
				.fromObject(map.get(CRMServiceConst.CRM_REQUEST_PARAMS).toString());
		//服务渠道(dbu渠道传CCI即可  目前只支持dbu渠道)
		String serviceChannel = MapUtils.getString(paramsMap, "serviceChannel", "");
		//服务站编号(服务站的授权编号)
		String stationNo = MapUtils.getString(paramsMap, "stationNo", "");
		//0：取消授权   1：撤回取消授权     目前只支持0，不支持1
		int type = MapUtils.getIntValue(paramsMap, "type", -1);

		// 校验参数是否为空
		if (StringUtils.isEmpty(serviceChannel) || StringUtils.isEmpty(stationNo) || type == -1) {
			ParameterTool.writeResponse(response, 1, "缺少必要参数");
			return;
		}

		if (type != 0 && type != 1) {
			ParameterTool.writeResponse(response, 1, "所传参数值有误");
			return;
		}

		if (type == 1) {   //撤回取消授权   目前暂不支持
			ParameterTool.writeResponse(response, 1, "暂不支持此类型操作");
			return;
		}

		CompanyT companyT = companyTDao.getCompanyInfoByCompanyNo(serviceChannel);
		if (!"CCI".equals(serviceChannel) || null == companyT) {
			ParameterTool.writeResponse(response, 1, "服务渠道所传有误，目前只支持CCI渠道");
			return;
		}
		Map<String, Object> ssRepairTMap = new HashMap<>();
		ssRepairTMap.put("stationNo", stationNo);
		ssRepairTMap.put("companyId", companyT.getId());
		List<Map<String, Object>> ssRepairTList = ssRepairTDao.getSSRepairTByServiceStationNoCompanyID(ssRepairTMap);
		if (CollectionUtils.isEmpty(ssRepairTList)) {
			ParameterTool.writeResponse(response, 1, "未查询到服务站授权信息");
			return;
		} else {
			//判断服务站是否多渠道授权，多渠道授权只作废调用这个接口的渠道授权关系,单渠道授权的话将这个服务站下所有人都置为终端用户
			long serviceStationId = MapUtils.getLongValue(ssRepairTList.get(0), "ServiceStationID", 0);
			int ssrepairCount = ssRepairTDao.getSsrepairCount(serviceStationId);
			//作废渠道授权关系
			ssRepairTDao.deleteSSRepairTByID(serviceStationId, companyT.getId());
			if (ssrepairCount == 1) {   //单渠道授权
				//作废服务站所有人员的所有角色关系
				userHasRolesTDao.deleteUserHasRolesTByUserId(serviceStationId);
				//维护终端用户角色到用户角色关系表
				userHasRolesTDao.insertUserHasRolesTByUserId(serviceStationId);
				//修改用户表服务站所有人员的用户组信息和服务站id字段
				userTDao.updateEndUserByUserId(serviceStationId);
			}
		}
		ParameterTool.writeSuccessResponse(response);
	}

	@Resource
	private EscalationReasonTDao escalationReasonTDao;
	@Resource
	private EscalationSolutionTDao escalationSolutionTDao;
	@Resource
	private EscalationOrderTDao escalationOrderTDao;
	@Resource
	private EscalationNotifyService escalationNotifyService;
	@Resource
	private CommonNotifyRecordTDao commonNotifyRecordTDao;
	@Resource
	private RelationShipTDao relationShipTDao;
	@Resource
	private EscalationServiceImpl escalationServiceImpl;


	@Override
	@Transactional
	public void escalation(Map<String, Object> map) throws Exception {
		LOG.info("SF反馈的专家解决方案：" + map);
		HttpServletResponse response = (HttpServletResponse) map.get("response");
		Map<String, Object> paramsMap = (Map<String, Object>) JSONObject
				.fromObject(map.get(CRMServiceConst.CRM_REQUEST_PARAMS).toString());
		String orderNo = MapUtils.getString(paramsMap, "orderNo");
		String company = MapUtils.getString(map, "company");
		String solution = MapUtils.getString(paramsMap, "solution");
		String status = MapUtils.getString(paramsMap, "status");

//		String orderNo = MapUtils.getString(paramsMap, "orderNo");
//		String cancelCause = MapUtils.getString(paramsMap, "cancelCause");
		if ("CCI".equals(company) || "DBU".equals(company)) {
			// 校验参数是否为空
			if (StringUtils.isEmpty(orderNo)) {
				LOG.error("orderNo不能为空");
				ParameterTool.writeResponse(response, 1, "orderNo不能为空");
				return;
			}
			if (StringUtils.isEmpty(solution)) {
				LOG.error("解决方案不能为空");
				ParameterTool.writeResponse(response, 1, "解决方案不能为空");
				return;
			}
			// 根据服务工单编号查询出对应的服务工单
			Map<String, Object> orderInfoMap = crmServiceDao.getOldOrderInfoByOrderNo(orderNo);
			if (orderInfoMap == null) {
				LOG.error(String.format("不存在编号:%s的服务工单", orderNo));
				ParameterTool.writeResponse(response, 1, "服务工单不存在");
				return;
			}
			Long orderId = MapUtils.getLong(orderInfoMap, "ID");

			EscalationOrderT escalationOrderT = escalationOrderTDao.selectByWorkOrderId(orderId);
			//主动升级工单id
			Long escalationId = escalationOrderT.getId();
			if (!StringUtils.isEmpty(status) && "6".equals(status)) {
				if (escalationOrderT.getStatus() == 4 || escalationOrderT.getStatus() == 5) {
					ParameterTool.writeErrorResponse(RequestContextHolder.getResponse(), -28);
					return;
				}
				try {
					// 加锁处理，避免发生多次注册。
					if (!redisClientUtils.lock("escalationRemind-" + escalationOrderT.getId(), 60L)) {
						ParameterTool.writeErrorResponse(RequestContextHolder.getResponse(), -98);
						return;
					}
					escalationOrderT.setUpdator(-1L);
					escalationOrderT.setUpdateTime(LocalTimeUtil.getRealCurrentTime());
					escalationOrderT.setStatus(TypeDictionary.ORDERTYPE_TECHNICIAN_CONFIRMING_FROMSERVICEEXPERT.getCode());
					int conOrder = escalationOrderTDao.updateByPrimaryKeySelective(escalationOrderT);
					if (conOrder < 1) {
						LOG.error(String.format("SF同步的解决方案后，修改主动升级工单报错", orderNo));
						ParameterTool.writeResponse(response, 1, "SF同步的解决方案后，修改主动升级工单报错");
						return;
					}
					List<UserT> expertList = escalationNotifyService.getExpert(escalationId);

					UserT user = new UserT();
					user.setId(0L);
					//新增：负责人表
					int conPrincipal = escalationServiceImpl.insertEscalationPrincipal("6", escalationId, null, user);
					if (conPrincipal < 1) {
						throw new RuntimeException();
					}

					//新增：流水(跟文芳沟通后，sf给的解决方案暂时不需要时间轴)
					int conFlow = escalationServiceImpl.insertEscalationFlowT(escalationId,
							TypeDictionary.FLOWTYPE_FEEDBACK_FROM_SERVICEEXPERT.getCode(),
							TypeDictionary.ORDERTYPE_TECHNICIAN_CONFIRMING_FROMSERVICEEXPERT.getCode(),
							user,null);
					if (conFlow < 1) {
						throw new RuntimeException();
					}
				} finally {
					redisClientUtils.delkey("escalationRemind-" + escalationOrderT.getId());
				}
				escalationOrderT.setUpdator(-1L);
				escalationOrderT.setUpdateTime(LocalTimeUtil.getRealCurrentTime());
				escalationOrderT.setStatus(TypeDictionary.ORDERTYPE_TECHNICIAN_CONFIRMING_FROMSERVICEEXPERT.getCode());
				int conOrder = escalationOrderTDao.updateByPrimaryKeySelective(escalationOrderT);
				if (conOrder < 1) {
					LOG.error(String.format("SF同步的解决方案后，修改主动升级工单报错", orderNo));
					ParameterTool.writeResponse(response, 1, "SF同步的解决方案后，修改主动升级工单报错");
					return;
				}
			}
			EscalationReasonT escalationReasonByOrderId = escalationReasonTDao.getEscalationReasonByOrderIdAndType(escalationId);
			Long reasonId = null;
			if (escalationReasonByOrderId != null) {
				 reasonId = escalationReasonByOrderId.getId();
			} else {
				LOG.error(String.format("工单没有升级原因", orderNo));
				ParameterTool.writeResponse(response, 1, "工单没有升级原因");
				return;
			}

			// 先查询是否已经存在解决方案
			EscalationSolutionT escalationSolutionT = escalationSolutionTDao.getLastEscalationSolutionByOrderIdAndReasonId(escalationId, reasonId);
			int conSolution = 0;
			if (escalationSolutionT == null) {
				//把SF同步的解决方案入库
				escalationSolutionT = new EscalationSolutionT();
				escalationSolutionT.setOrderId(escalationId);
				escalationSolutionT.setOrderReasonId(reasonId);
				escalationSolutionT.setProviderId(-1L);
				escalationSolutionT.setSolution(solution);
				escalationSolutionT.setAttachmentList(new JSONArray().toString());
				escalationSolutionT.setFlag(0);
				escalationSolutionT.setCreator(-1L);
				escalationSolutionT.setCreateTime(LocalTimeUtil.getRealCurrentTime());
				conSolution = escalationSolutionTDao.insertSelective(escalationSolutionT);
			} else {
				escalationSolutionT.setSolution(solution);
				escalationSolutionT.setUpdateTime(LocalTimeUtil.getRealCurrentTime());
				conSolution = escalationSolutionTDao.updateByPrimaryKeySelective(escalationSolutionT);
			}

			if (conSolution < 1) {
				LOG.error(String.format("SF同步的解决方案入库报错", orderNo));
				ParameterTool.writeResponse(response, 1, "SF同步的解决方案入库报错");
				return;
			}

			try {
				String content = "主动升级任务【康明斯反馈】"+orderNo+"，已收到专家反馈，请前往APP查看详情。";
				String title = "主动升级任务"+orderNo+"【待技师确认】";
				// 专家
				List<UserT> expertList = escalationNotifyService.getExpert(escalationId);
				sendSMS(0L, "1", escalationId, expertList, content);
				push(0L, "1", escalationId, expertList, title, content);
				//sendEmail(0L, "1", escalationId, expertList, title, content);
				// 区域工程师
				List<UserT> engineersList = escalationNotifyService.getEngineers(escalationId);
				sendSMS(0L, "1", escalationId, engineersList, content);
				push(0L, "1", escalationId, engineersList, title, content);
				//sendEmail(0L, "1", escalationId, engineersList, title, content);
				//技师
				List<UserT> technicianList = escalationNotifyService.getTechnicians(escalationId);
				sendSMS(0L, "1", escalationId, technicianList, content);
				push(0L, "1", escalationId, technicianList, title, content);
				//sendEmail(0L, "1", escalationId, technicianList, title, content);
			} catch (Exception e) {
				LOG.error(e.getMessage());
			}
			// 查询到主动升级工单的负责人，然后发信息

		}
		ParameterTool.writeSuccessResponse(response);
	}
	private void sendSMS(Long configId, String category, Long uniqueId, List<UserT> userTList, String content) {
		for (UserT userT : userTList) {
			SmsUtils.sendMessage(userT.getPhone(), content);
			CommonNotifyRecordT recordT = new CommonNotifyRecordT();
			recordT.setCategory(category);
			recordT.setOrderId(uniqueId);
			recordT.setConfigId(configId);
			recordT.setReceiverId(userT.getId());
			recordT.setContent(content);
			recordT.setStatus("1");
			recordT.setSendType(NotifyMannerType.SMS.getCode());
			recordT.setCreator(userT.getId());
			recordT.setCreateTime(LocalTimeUtil.getRealCurrentTime());
			commonNotifyRecordTDao.insertSelective(recordT);
		}
		System.out.println("发送短信：" + content + "|人数：" + userTList.size());
	}

	private void push(Long configId, String category, Long uniqueId, List<UserT> userTList, String title, String content) {
		for (UserT userT : userTList) {
			String clientId = redisClientUtils.hget(RedisKeys.geTuiKey(), userT.getUserName());
			if (StringUtils.isEmpty(clientId)) {
				// redis中不存在，查询数据库
				RelationShipT relationShipT = relationShipTDao.getClientIdByUserNameString(userT.getUserName());
				if (null != relationShipT) {
					clientId = relationShipT.getClientId();
				}
			}

			CommonNotifyRecordT recordT = new CommonNotifyRecordT();
			recordT.setCategory(category);
			recordT.setOrderId(uniqueId);
			recordT.setConfigId(configId);
			recordT.setReceiverId(userT.getId());
			recordT.setContent(content);
			recordT.setFlag(0);
			recordT.setSendType(NotifyMannerType.APP.getCode());

			// ClientId不为空时，进行推送操作，为空时进行异常记录
			if (StringUtils.isNotEmpty(clientId)) {
				// 发送推送操作
				NotifyUtil.push2Single(clientId, title, content, 2, content);
				recordT.setStatus("1");
			} else {
				recordT.setStatus("2");
				recordT.setExceptionInfo("用户ClientId不存在");
			}

			recordT.setCreator(userT.getId());
			recordT.setCreateTime(LocalTimeUtil.getRealCurrentTime());
			commonNotifyRecordTDao.insertSelective(recordT);
		}
		System.out.println("发送推送：" + content + "|人数：" + userTList.size());
	}

	private void sendEmail(Long configId, String category, Long uniqueId, List<UserT> userTList, String title, String content) {
		for (UserT userT : userTList) {
			String email = userT.getEmail();

			CommonNotifyRecordT recordT = new CommonNotifyRecordT();
			recordT.setCategory(category);
			recordT.setOrderId(uniqueId);
			recordT.setConfigId(configId);
			recordT.setReceiverId(userT.getId());
			recordT.setContent(content);
			recordT.setFlag(0);
			recordT.setSendType(NotifyMannerType.EMAIL.getCode());
			if (StringUtils.isNotEmpty(email)) {
				try {
					Thread t = Thread.currentThread();
					String name = t.getName();
					LOG.info("发送邮件开始："+name);
					MailUtil.sendMail(email, title, content);
					recordT.setStatus("1");
					LOG.info("发送邮件结束："+name);
				} catch (Exception e) {
					LOG.error(e.getMessage(), e);
					recordT.setStatus("2");
					recordT.setExceptionInfo("发送邮件发生异常：" + e.getMessage());
				}
			} else {
				recordT.setStatus("2");
				recordT.setExceptionInfo("接收人邮箱为空，无法发送，接收人手机号：" + userT.getPhone());
			}
			recordT.setCreator(userT.getId());
			recordT.setCreateTime(LocalTimeUtil.getRealCurrentTime());
			commonNotifyRecordTDao.insertSelective(recordT);
		}
	}

	private static String crmCancelWorkOrderSMSMsg = "工单编号%s，工单任务已被取消，请悉知。有任何问题，请联系康明斯中国在线400-810-5252";
	private static String crmCancelWorkOrderAPPMsg = "您有工单取消，工单号%s，请查看。";
	private static String crmDBUCancelWorkOrderSMSMsg = "工单编号%s，属于\"%s\"-%s，工单任务已被取消，请悉知。有任何问题，请联系康明斯中国在线400-810-5252";
	private static String crmDBUCancelWorkOrderAPPMsg = "您有工单取消，工单号%s，属于\"%s\"-%s，请查看。";
	/**
	 * 给当前工单的用户、服务站站长\信息员、区域工程师、技师推送消息
	 */
	private void sendMessage(Long orderId, String orderNo, Long customerId, String customerPhone, Long serviceStationId) {

		// 查询出服务的站长、信息员
		List<Long> serviceStationUserIdList = null;
		if (serviceStationId != null) {
			serviceStationUserIdList = serviceStationDao.getServiceStationUserIdList(serviceStationId);
		}

		// 查询出工单对应的技师
		List<Long> technicianIdList = workOrderPrincipalTDao.getTechnicianIdsByOrderId(orderId);

		// 查询出工单的区域工程师
		Map<String, Object> operatorUser = workOrderOperatorRelationDao.getOperatorUserIdByOrderId(orderId);


		Long operatorUserId = null;
		String operatorUserPhone = null;
		if (null != operatorUser) {
			// 区域工程师的userId
			operatorUserId = MapUtils.getLong(operatorUser, "userId");
			// 区域工程师的电话
			operatorUserPhone = MapUtils.getString(operatorUser, "phone");
		}

		List<Long> userIds = new ArrayList<>();

		// 如果用户id不为空说明当前用户为e路康明斯用户
		/*	if(customerId != null) {
				userIds.add(customerId);
			}*/

		// 当前工单是否有对应的服务站
		if (CollectionUtils.isNotEmpty(serviceStationUserIdList)) {
			userIds.addAll(serviceStationUserIdList);
		}
		// 当前工单是否有对应的技师
		if (CollectionUtils.isNotEmpty(technicianIdList)) {
			userIds.addAll(technicianIdList);
		}
		// 当前工单对应的区域工程师
		// 当前工单对应的区域工程师
		if (operatorUserId != null) {
			userIds.add(operatorUserId);
		}

		LOG.info("<400取消消息接收人>" + userIds);

		String currentTime = LocalTimeUtil.getRealCurrentTime();
		List<Map<String, Object>> notifyRecordTMapList = new ArrayList<>();

		// 如果userIds为空说明当前工单的用户为非e路康明斯用户
		if (!userIds.isEmpty()) {
			// 推送消息，生成消息记录
			List<Map<String, Object>> userPhoneClient = userTDao.getPhoneAndClientIdByUserIds(userIds);
			if (CollectionUtils.isNotEmpty(userPhoneClient)) {
				for (Map<String, Object> userMap : userPhoneClient) {
					Long userId = MapUtils.getLong(userMap, "userId");
					String phone = MapUtils.getString(userMap, "phone");
					String clientId = MapUtils.getString(userMap, "clientId");

					// 发送短信
					notifyRecordTMapList.add(doSendSMS(orderId, orderNo, userId, phone, currentTime));
					// App推送
					notifyRecordTMapList.add(doSendAPP(orderId, orderNo, userId, clientId, currentTime));
				}
			}
		}

		// 如果区域工程师的userId为空时，说明区域工程师不是e路用户，不会有clientID只需要推送短信即可
		if (operatorUserId == null) {
			// 发送短信
			notifyRecordTMapList.add(doSendSMS(orderId, orderNo, null, operatorUserPhone, currentTime));
		}

		// 这里判断目的，如果customerId为空时，userPhoneClient并不会包含这个用户的发送信息，所以需要单独给这个用户发送(只需要发送短信)
		// 简单的说，非康明斯用户没有ClientId只需要发送短信即可
		//if(customerId == null) {
		// 发送短信
		//	notifyRecordTMapList.add(doSendSMS(orderId, orderNo, null, customerPhone, currentTime));
		//}

		// 保存消息推送记录
		if (CollectionUtils.isNotEmpty(notifyRecordTMapList)) {
			workOrderRePairDao.saveMsgOperation(notifyRecordTMapList);
		}
	}


	/**
	 * 发送短信
	 * 返回消息记录
	 */
	private Map<String, Object> doSendSMS(Long orderId, String orderNo, Long userId, String customerPhone, String currentTime) {
		WorkOrderT workOrderT = workOrderTDao.getWorkOrderTByOrderId(orderId);
		String content = "";
		if(workOrderT.getOrderChannel() == 1){
			content = String.format(crmDBUCancelWorkOrderSMSMsg, orderNo,workOrderT.getSellType(),workOrderT.getServiceSubtype());
		} else {
			content = String.format(crmCancelWorkOrderSMSMsg, orderNo);
		}
		String result = "fail";
		if (StringUtils.isNotEmpty(customerPhone)) {
			result = SmsUtils.sendMessage(customerPhone, content);
		}
		return workOrderTServiceImpl.saveMsgOperation(orderId, 9, 4, userId, content, 1, currentTime, sendResult(customerPhone, result), -1L);
	}

	/**
	 * 发送app消息
	 * 返回消息记录
	 */
	private Map<String, Object> doSendAPP(Long orderId, String orderNo, Long userId, String clientId, String currentTime) {
		WorkOrderT workOrderT = workOrderTDao.getWorkOrderTByOrderId(orderId);
		String content = "";
		if(workOrderT.getOrderChannel() == 1){
			content = String.format(crmDBUCancelWorkOrderAPPMsg, orderNo,workOrderT.getSellType(),workOrderT.getServiceSubtype());
		} else {
			content = String.format(crmCancelWorkOrderAPPMsg, orderNo);
		}
		boolean result = false;
		if (StringUtils.isNotEmpty(clientId)) {
			result = NotifyUtil.push2Single(clientId, content, content);
		}
		return workOrderTServiceImpl.saveMsgOperation(orderId, 9, 4, userId, content, 2, currentTime, sendResult(clientId, result), -1L);
	}


	private String sendResult(Object arg1, Object arg2) {
		return String.format("%s已发送状态:%s", arg1, arg2);
	}

	private void saveHisDealerInfoForPortal(Map<String, Object> serviceStationInfoMap) {
		int count = crmServiceDao.checkHisDealerInfoExits(serviceStationInfoMap);
		if (count == 0) {
			crmServiceDao.insertHisDealerInfoForPortal(serviceStationInfoMap);
		} else if (count == 1) {
			crmServiceDao.updateHisDealerInfoForPortal(serviceStationInfoMap);
		} else {
			LOG.error("DealerInfo_T - save Error:" + serviceStationInfoMap.get("ServiceStationId")
					+ "has one more rows!");
		}
	}

	@Override
	public String syncIndividualCasesSave(Map<String, Object> map) {
		//--
		HttpServletResponse response = (HttpServletResponse) map.get("response");
		if (null == map.get(CRMServiceConst.CRM_REQUEST_PARAMS) || StringUtils.isBlank(MapUtils.getString(map, CRMServiceConst.CRM_REQUEST_PARAMS))) {
			JSONObject resultObj = new JSONObject();
			resultObj.put("status", -99);
			resultObj.put("msg", "参数不能为空");
			ParameterTool.writeResponse(response, resultObj.toString());
			return null;
		}

		LOG.info(String.format("同步工单超时原因个案详情", map.get(CRMServiceConst.CRM_REQUEST_PARAMS)));
		//转成参数

		com.alibaba.fastjson.JSONArray jsonArray = JSON.parseArray(JSON.toJSON(map.get(CRMServiceConst.CRM_REQUEST_PARAMS)).toString());
		//获取服务编号
		if (CollectionUtils.isEmpty(jsonArray)) {
			JSONObject resultObj = new JSONObject();
			resultObj.put("status", -99);
			resultObj.put("msg", "参数为空");
			ParameterTool.writeResponse(response, resultObj.toString());
			return null;
		}
		List<String> orderNoList = jsonArray.stream().map(e -> JSON.parseObject(e.toString()).getString("orderNo")).collect(Collectors.toList());
		List<WorkOrderT> workOrderTList = workOrderTDao.selectWorkOrderByOrderNoList(orderNoList);
		if (null == workOrderTList || workOrderTList.size() != orderNoList.size()) {
			JSONObject resultObj = new JSONObject();
			resultObj.put("status", -99);
			resultObj.put("msg", "参数不正确");
			LOG.info("个案进展更新  params 参数为: " + com.alibaba.fastjson.JSONObject.toJSONString(orderNoList));
			LOG.info("个案进展更新  查出来的结果为: " + com.alibaba.fastjson.JSONObject.toJSONString(workOrderTList));
			ParameterTool.writeResponse(response, resultObj.toString());
			return null;
		}
		Map<String, WorkOrderT> workOrderTMap = workOrderTList.stream().collect(Collectors.toMap(WorkOrderT::getOrderNo, e -> e));
		for (Object o : jsonArray) {
			String orderNo = JSON.parseObject(JSON.toJSONString(o)).getString("orderNo");
			WorkOrderT workOrderT = workOrderTMap.get(orderNo);
			if (workOrderT != null) {
				String individualCases = JSON.parseObject(JSON.toJSONString(o)).getString("individualCases");
				WorkOrderIndividualCases workOrderIndividualCases = new WorkOrderIndividualCases();
				workOrderIndividualCases.setOrderId(workOrderT.getId());
				workOrderIndividualCases.setIndividualCases(individualCases);
				workOrderIndividualCases.setFlag(0);
				workOrderIndividualCases.setCreator(-1L);
				workOrderIndividualCases.setCreateTime(LocalTimeUtil.getRealCurrentTime());
				workOrderIndividualCasesMapper.insert(workOrderIndividualCases);
			}
		}
		JSONObject resultObj = new JSONObject();
		resultObj.put("status", 0);
		resultObj.put("msg", "个案添加成功");
		resultObj.put("data", new JSONObject());
		ParameterTool.writeResponse(response, resultObj.toString());
		return null;
	}
}

